<?php
namespace app\common\service\member;
use app\common\cache\member\MemberAccountCache;
use app\common\model\member\MemberAccountModel;
use app\common\model\order\ShopOrderModel;
use app\common\model\product\ShopProductTypeModel;
use app\common\model\setting\SettingPriceRangeModel;
use app\common\model\setting\SettingStorePlatformModel;
use app\common\service\api\TaoceSdkService;
use app\common\service\api\VrabbitSdkService;
use app\common\service\file\FileService;
use app\common\service\member\SettingService as MemberSetting;
use app\common\service\setting\RegionService;
use app\common\service\setting\SettingPriceRangeService;
use app\common\service\setting\SettingStorePlatformService;
use app\common\service\system\SettingService as SystemSettingService;
use app\common\service\webscoket\CacheRedisService;
use DateTime;
use think\facade\Db;
use think\facade\Log;

/**
 * 接单账号
 */
class MemberAccountService
{
    /**
     * 添加、修改字段
     * @var array
     */
    public static $edit_field = [
        'id/d'=>null,//主键ID
        'title/s'=>null,//标题
        'content/s'=>null,//内容
        'is_member/d'=>0,//是否会员，1是0否
        'is_disable/d'=>0,//是否禁用，1是0否
        'is_order_taking/d'=>0,//是否开启接单：1是、0否
        'member_id/d'=>null,//买手ID
        'store_platform_id/d'=>null,//店铺平台ID
        'setting_store_type_ids/a'=>null,//商品类目ID
        'nickname/s'=>null,//接单号昵称
        'accname/s'=>null,//接单号账号
        'level/d'=>null,//信用等级
        'sex/d'=>null,//性别：0、位置 1、男 2、女
        'age/d'=>null,//年龄
        'age_index/d'=>null,//年龄段
        'integral/d'=>null,//淘气值
        'authority/d'=>null,//降权
        'taoling/d'=>null,//淘龄
        'evaluate_image_id/d'=>null,//订单评价截图
        'last_month_image_id/d'=>null,//上月订单截图
        'month_image_id/d'=>null,//上上月订单截图
        'personal_center_image_id/d'=>null,//个人中心截图
        'consignee/s'=>null,//收货人
        'phone/s'=>null,//联系电话
        'region_id/s'=>null,//收货地址
        'address/s'=>null,//收货详细地址
        'status/d'=>0,//状态：0、待审核 1、审核成功 2、审核失败 3、验号
        'auth_msg/s'=>null,//审核原因
        'sort/d'=>250,//排序
        'remark/s'=>null,//备注
        'ip/s'=>null,//ip地址
        'issue_comment_tax/d'=>0,//发出好评率%
        'receive_comment_tax/d'=>0,//收到好评率%
        'bad/d'=>0,//差评
        'find_fault/d'=>0,//找茬
        'spot_check/d'=>0,//抽检
        'refund/d'=>0,//退款
        'combating_counterfeits/d'=>0,//打假
        'serial_num/d'=>0,//各店铺平台下添加账号时的序号
    ];
    /**
     * 接单账号列表
     *
     * @param array  $where 条件
     * @param int    $page  页数
     * @param int    $limit 数量
     * @param array  $order 排序
     * @param string $field 字段
     *
     * @return array
     */
    public static function list($where = [], $page = 1, $limit = 10,  $order = [], $field = '')
    {
        $model = new MemberAccountModel();
        $pk = $model->getPk();
        if (empty($field)) {
            $field = 'id,title,content,is_member,is_disable,is_order_taking,create_time,update_time,auth_time,register_time,order_taking_time,member_id,store_platform_id,setting_store_type_ids,nickname,accname,level,sex,age,age_index,integral,authority,taoling,evaluate_image_id,last_month_image_id,month_image_id,personal_center_image_id,consignee,phone,region_id,address,status,auth_msg,sort,remark,ip,issue_comment_tax,receive_comment_tax,bad,find_fault,spot_check,refund,combating_counterfeits,serial_num';
        }
        if (empty($order)) {
            $order = [$pk => 'desc'];
        }
        //条件
        foreach ($where as $key=>$val){
            if($val[0] == 'setting_store_type_ids' && isset($val[2])){
                $idList =$val[2];
                $model = $model->where(function($query) use ($idList, $val) {
                    foreach ($idList as $id) {
                        $query->whereOrRaw("FIND_IN_SET(?, setting_store_type_ids)", [$id]);
                    }
                });
                unset($where[$key]);
            }
        }
        $with = [];
        //用户信息
        if (strpos($field, 'member_id') !== false) {
            $merber_with = ['member' => function ($query) {
                $query->field('member_id,nickname,username');
            }];
            $with = array_merge($with,$merber_with);
        }
        //平台信息
        if (strpos($field, 'store_platform_id') !== false) {
            $platform_with = ['platform' => function ($query) {
                $query->with(['image'])->append(['image_url'])->hidden(['image'])->field('id,title,image_id');
            }];
            $with = array_merge($with,$platform_with);
        }
        if ($page == 0 || $limit == 0) {
            return $model->with($with)->field($field)->where($where)->order($order)->select()->toArray();
        }
        $count = $model->where($where)->count();
        $pages = ceil($count / $limit);
        $list = $model->with($with)->field($field)->where($where)->page($page)->limit($limit)->order($order)->select()->toArray();
        $age_list = SettingPriceRangeService::getAgeList();
        foreach ($list as $k => $v) {
            //查询等级名称
            $list[$k]['level_str'] = MemberAccountModel::getLevel($v['level'],2);
            //收货地区
            $list[$k]['region_title'] = "";
            if($v['region_id']){
                $region = RegionService::info($v['region_id']);
                if(isset($region['region_fullname'])){
                    $list[$k]['region_title'] = $region['region_fullname'];
                }
            }
            //查询类目名称
            $list[$k]['setting_store_type_title'] ="";
            if($v['setting_store_type_ids']){
                $titles = Db::name('setting_store_type')
                    ->where('id','in',explode(',',$v['setting_store_type_ids']))
                    ->field('title')
                    ->select()->toArray();
                $list[$k]['setting_store_type_title'] =implode(',',array_column($titles,'title'));
            }
            //年龄段
            $list[$k]['age_index_title'] ='';
            foreach ($age_list as $key=>$val){
                if($v['age_index'] == $val['value']){
                    $list[$k]['age_index_title'] =$val['label'];
                    break;
                }
            }
        }
        return compact('count', 'pages', 'page', 'limit', 'list');
    }
    //查询参数
    public static function getParams()
    {
        $level_list = MemberAccountModel::LEVEL;
        $age_list = SettingPriceRangeService::getAgeList();
        $where[] = ['is_disable','=',0];
        $where[] = ['is_delete','=',0];
        $platform_list = SettingStorePlatformService::list($where,0,0, [],'id as value,title as label,is_disable as disable,code');
        foreach ($platform_list as $key=>$val){
            if($val['code']=='tianmao'){
                unset($platform_list[$key]);
                break;
            }
        }
        // 重新排列数组索引
        $platform_list = array_values($platform_list);
        return compact('level_list','age_list','platform_list');
    }
    /**
     * 接单账号信息
     *
     * @param int  $id   接单账号id
     * @param bool $exce 不存在是否抛出异常
     *
     * @return array|Exception
     */
    public static function info($id, $exce = true)
    {
        $info = MemberAccountCache::get($id);
        if (empty($info)) {
            $model = new MemberAccountModel();
            $info = $model->find($id);
            if (empty($info)) {
                if ($exce) {
                    exception('接单账号不存在：' . $id);
                }
                return [];
            }
            //购物类目
            $info = $info->toArray();
            if($info['setting_store_type_ids']){
                $info['setting_store_type_ids'] = explode(",",$info['setting_store_type_ids']);
                foreach ($info['setting_store_type_ids'] as &$val) {
                    $val = (int) $val;
                }
            }
            //收货地区
            if($info['region_id']){
                $info['region_id'] = (int)$info['region_id'];
            }
            //图片
            if($info['evaluate_image_id']){
                $file = FileService::info($info['evaluate_image_id']);
                if($file && isset($file['file_url'])){
                    $info['evaluate_image_url'] =$file['file_url'];
                }
            }
            if($info['last_month_image_id']){
                $file1 = FileService::info($info['last_month_image_id']);
                if($file1 && isset($file1['file_url'])){
                    $info['last_month_image_url'] =$file1['file_url'];
                }
            }
            if($info['month_image_id']){
                $file2 = FileService::info($info['month_image_id']);
                if($file2 && isset($file2['file_url'])){
                    $info['month_image_url'] =$file2['file_url'];
                }
            }
            if($info['personal_center_image_id']){
                $file2 = FileService::info($info['personal_center_image_id']);
                if($file2 && isset($file2['file_url'])){
                    $info['personal_center_image_url'] =$file2['file_url'];
                }
            }
            MemberAccountCache::set($id, $info);
        }
        return $info;
    }
    /**
     * 接单账号添加
     *
     * @param array $param 接单账号信息
     *
     * @return array|Exception
     */
    public static function add($param)
    {
        $model = new MemberAccountModel();
        $pk = $model->getPk();
        unset($param[$pk]);
        $param['create_uid']  = user_id();
        $param['create_time'] = datetime();
        if(isset($param['setting_store_type_ids']) && $param['setting_store_type_ids']){
            $param['setting_store_type_ids'] = implode(',',$param['setting_store_type_ids']);
        }
        $model->save($param);
        $id = $model->$pk;
        if (empty($id)) {
            exception();
        }
        $param[$pk] = $id;
        return $param;
    }
     /**
     * 接单账号修改
     *
     * @param int|array $ids   接单账号id
     * @param array     $param 接单账号信息
     *
     * @return array|Exception
     */
    public static function edit($ids, $param = [])
    {
        $model = new MemberAccountModel();
        $pk = $model->getPk();
        unset($param[$pk], $param['ids']);
        $param['update_uid']  = user_id();
        $param['update_time'] = datetime();
        if(isset($param['setting_store_type_ids']) && $param['setting_store_type_ids']){
            $param['setting_store_type_ids'] = implode(',',$param['setting_store_type_ids']);
        }
        $res = $model->where($pk, 'in', $ids)->update($param);
        if (empty($res)) {
            exception();
        }
        $param['ids'] = $ids;
        MemberAccountCache::del($ids);
        return $param;
    }
    /**
     * 接单账号删除
     *
     * @param array $ids  接单账号id
     * @param bool  $real 是否真实删除
     *
     * @return array|Exception
     */
    public static function dele($ids, $real = false)
    {
        $model = new MemberAccountModel();
        $pk = $model->getPk();
        if ($real) {
            $res = $model->where($pk, 'in', $ids)->delete();
        } else {
            $update = delete_update();
            $res = $model->where($pk, 'in', $ids)->update($update);
        }
        if (empty($res)) {
            exception();
        }
        $update['ids'] = $ids;
        MemberAccountCache::del($ids);
        return $update;
    }

    /**
     * 组装查询SQL
     * @Author: 易军辉
     * @DateTime:2024-06-26 19:56
     * @param $where
     * @param $order
     * @return string
     */
    private static function getListSql($where = [], $order = [],$field = '')
    {
        /***************************查询字段***********************************************/
        //已接单状态
        $status_str = ShopOrderModel::getStatus('o_delivery',1).","
            .ShopOrderModel::getStatus('o_evaluate',1).","
            .ShopOrderModel::getStatus('o_auth',1).","
            .ShopOrderModel::getStatus('o_success',1);
        //待操作状态
        $operation_status = ShopOrderModel::getStatus('o_listing',1).","
            .ShopOrderModel::getStatus('o_select',1).","
            .ShopOrderModel::getStatus('o_taking',1).","
            .ShopOrderModel::getStatus('o_operation',1);
        if (empty($field)) {
            $field = 'platform.title as platform_title,
            platform.image_id as platform_image_id,
            member.nickname as member_nickname,
            member.username as member_username,
            member.login_ip as member_login_ip,
            member.login_region as member_login_region,
            -- 统计 今日 内订单数量
            (SELECT COUNT(o.id) 
             FROM ya_shop_order AS o 
             WHERE o.member_account_id = a.id  and o.is_delete =0 and o.status in ('.$status_str.')
               AND o.meet_time >= CURDATE()) AS orders_today,
            -- 统计 7 天内订单数量
            (SELECT COUNT(o.id) 
             FROM ya_shop_order AS o 
             WHERE o.member_account_id = a.id and o.is_delete =0 and o.status in ('.$status_str.')
               AND o.meet_time >= NOW() - INTERVAL 7 DAY) AS orders_last_7_days,
             -- 统计 15 天内订单数量
            (SELECT COUNT(o.id) 
             FROM ya_shop_order AS o 
             WHERE o.member_account_id = a.id and o.is_delete =0 and o.status in ('.$status_str.')
               AND o.meet_time >= NOW() - INTERVAL 15 DAY) AS orders_last_15_days,
             -- 统计 30 天内订单数量
            (SELECT COUNT(o.id) 
             FROM ya_shop_order AS o 
             WHERE o.member_account_id = a.id and o.is_delete =0 and o.status in ('.$status_str.')
               AND o.meet_time >= NOW() - INTERVAL 30 DAY) AS orders_last_30_days,
             -- 投诉数量
             (SELECT count(appeal.id)
              FROM ya_shop_order_appeal AS appeal
              WHERE appeal.member_account_id = a.id and appeal.is_disable=0 and appeal.is_delete=0
             ) AS appeal_num,
             -- 最后接单时间
            (SELECT max(o.meet_time) as meet_time
             FROM ya_shop_order AS o 
             WHERE o.member_account_id = a.id and o.is_delete =0 and o.status in ('.$status_str.')
             ) AS orders_last_time,
            a.*';
        }
        /***************************组装条件***********************************************/
        $where_sql = " member.is_order_taking=1 ";
        foreach ($where as $key=>$val){
            if($where_sql!=""){
                $where_sql .=" and ";
            }
            if($val[0] == 'platform_ids' && isset($val[2])) {
                $where_sql .= " platform.id in(" . implode(',', $val[2]) . ") ";
            }else if($val[0] == 'setting_store_type_ids' && isset($val[2])) {
                $idList =$val[2];
                $where_sql .=" ( ";
                foreach ($idList as $id_k=>$id) {
                    if($id_k!=0){
                        $where_sql .=" or ";
                    }
                    $where_sql .=" (FIND_IN_SET( ".$id.", a.setting_store_type_ids )) ";
                }
                $where_sql .= " ) ";
            }else if(is_array($val[2])) {
                $where_sql .= " a." . $val[0] . " " . $val[1] . "(" . implode(',', $val[2]) . ")";
            }else if($val[0] == 'status' && $val[2]>=0) {
                $where_sql .= " a." . $val[0] . " " . $val[1] . " '" . $val[2] . "' ";
            }else if($val[1] == 'is'){
                $where_sql .=" a.".$val[0]." ".$val[1]." ".$val[2];
            }else{
                $where_sql .=" a.".$val[0]." ".$val[1]." '".$val[2]."' ";
            }
        }
//        echo $where_sql;exit();
        /***************************组装排序***********************************************/
        $order_sql = "";
        foreach ($order as $key=>$val){
            if($order_sql!=""){
                $order_sql .=" , ";
            }
            $order_sql .="a.".$key." ".$val." ";
        }
        if($order_sql == ""){
            $order_sql = "a.member_id asc,a.id desc";
        }
        /***************************查询商家是否指定买手分组***********************************************/
        $group_list = Db::name('merchant_attributes')->where('mer_id',mer_id())->field('group_id')->select()->toArray();
        if($group_list){
            $group_ids = "";
            foreach ($group_list as $key=>$val){
                 if($group_ids!=""){
                     $group_ids .=",";
                 }
                $group_ids .=$val['group_id'];
            }
            if($where_sql !=""){
                $where_sql .=" and ";
            }
            $where_sql .=" member.member_id in(
					SELECT member_a.member_id from ya_member_attributes as member_a where member_a.group_id in(".$group_ids.") GROUP BY member_a.member_id
				) ";
        }
        /***************************买家操作中单数限制***********************************************/
        $setting = SystemSettingService::info('order_member_operation_num');
        $order_member_operation_num = 0;
        if(isset($setting['order_member_operation_num']) && $setting['order_member_operation_num']>0){
            $order_member_operation_num =$setting['order_member_operation_num'];
        }
        if($order_member_operation_num>0){
            if($where_sql !=""){
                $where_sql .=" and ";
            }
            $where_sql .= " (SELECT COUNT(o.id) 
             FROM ya_shop_order AS o 
             WHERE (
                        (o.member_id = a.member_id)
                        or (o.pending_member_id = a.member_id and o.pending_time>=NOW())
                    )
                    and o.is_delete =0 
                    and o.status in (".$operation_status.")
              )<".$order_member_operation_num;
        }
        /***************************接单账号黑名单***********************************************/
        $merchant_blacklist = Db::name('merchant_blacklist')
            ->where('mer_id',mer_id())
            ->where('is_disable',0)
            ->where('is_delete',0)
            ->field('member_account_id')
            ->group('member_account_id')
            ->select()
            ->toArray();
        if(count($merchant_blacklist)>0){
            if($where_sql !=""){
                $where_sql .=" and ";
            }
            $where_sql .=" a.id not in(". implode(',',array_column($merchant_blacklist,'member_account_id')).") ";
        }

        $sql = <<<SQL
            SELECT 
                 {$field}
                FROM ya_member_account AS a
                -- 关联店铺平台
                LEFT JOIN ya_setting_store_platform AS platform ON a.store_platform_id = platform.id
                -- 关联买手	
                LEFT JOIN ya_member AS member ON a.member_id = member.member_id
            WHERE
                {$where_sql}
            ORDER BY 
                {$order_sql}
        SQL;
        return $sql;
    }

    /**
     * 查询自选买号
     * @Author: 易军辉
     * @DateTime:2024-06-26 19:11
     * @param $where
     * @param $page
     * @param $limit
     * @param $order
     * @param $field
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getAccounts($where = [], $page = 1, $limit = 10,  $order = [], $field = '')
    {
        $sql = self::getListSql($where,$order,$field);
        if ($page == 0 || $limit == 0) {
            return Db::query($sql);
        }
        $count =  Db::query("select count(*) as count from (".$sql.") as co");
        $count=$count[0]['count'];
        $pages = ceil($count / $limit);
        // 计算偏移量
        $offset = ($page - 1) * $limit;
        $list = Db::query($sql. " LIMIT $offset, $limit");
        foreach ($list as $k=>$v) {
            //查询等级名称
            $list[$k]['level_str'] = MemberAccountModel::getLevel($v['level'],2);
            //收货地区
            $list[$k]['region_title'] = "";
            if($v['region_id']){
                $region = RegionService::info($v['region_id']);
                if(isset($region['region_fullname'])){
                    $list[$k]['region_title'] = $region['region_fullname'];
                }
            }
            //查询类目名称
            $list[$k]['setting_store_type_title'] =[];
            if($v['setting_store_type_ids']){
                $titles = Db::name('setting_store_type')
                    ->where('id','in',explode(',',$v['setting_store_type_ids']))
                    ->field('title')
                    ->select()->toArray();
                $list[$k]['setting_store_type_title'] =array_column($titles,'title');
            }
            //店铺平台图片
            if(isset($v['platform_image_id']) && $v['platform_image_id']){
                $file = FileService::info($v['platform_image_id']);
                if($file && isset($file['file_url'])){
                    $list[$k]['platform_image_url'] =$file['file_url'];
                }
            }
        }
        return compact('count', 'pages', 'page', 'limit', 'list');
    }

    /**
     * 账号保存
     * @Author: 易军辉
     * @DateTime:2024-08-06 20:39
     * @param $param
     * @return mixed
     * @throws \think\Exception
     */
    public static function save($param)
    {
        $model = new MemberAccountModel();
        $pk = $model->getPk();
        /*******************相关参数验证***************************/
        $platform = SettingStorePlatformService::info($param['store_platform_id'],true,'id,title,code,evaluate_image_id,last_month_image_id,month_image_id,personal_center_image_id');
        if($platform['code'] == SettingStorePlatformModel::CODE_TB){
            if(!array_key_exists('taoling', $param) || $param['taoling']===null){
                exception('请输入淘龄');
            }
            if(!array_key_exists('level', $param) || $param['level']===null){
                exception('请选择信用等级');
            }

            if(!array_key_exists('integral', $param) || $param['integral']===null){
                exception('请输入淘气值');
            }
        }
        if($platform['evaluate_image_url'] && !isset($param['evaluate_image_id']) && !$param['evaluate_image_id']){
            exception('请上传订单评价截图');
        }
        if($platform['last_month_image_url'] && !isset($param['last_month_image_id']) && !$param['last_month_image_id']){
            exception('请上传上月订单截图');
        }
        if($platform['month_image_url'] && !isset($param['month_image_id']) && !$param['month_image_id']){
            exception('请上传上上月订单截图');
        }
        if($platform['personal_center_image_url'] && !isset($param['personal_center_image_id']) && !$param['personal_center_image_id']){
            exception('请上传个人资料截图');
        }
        // 查找是否已有记录
        $existingModel = $model->where('member_id', $param['member_id'])->where('id',(isset($param[$pk])?$param[$pk]:0))->find();
        unset($param[$pk]);
        //验号
        if($platform['code'] == SettingStorePlatformModel::CODE_TB){
            if(isset($existingModel) && $existingModel['status'] ==1){
                //审核通过的不进行验号
            }else{
                $param = self::verifyAccount($param);
            }
        }
        //常购类目处理
        if(isset($param['setting_store_type_ids']) && $param['setting_store_type_ids']){
            $param['setting_store_type_ids'] = implode(',',$param['setting_store_type_ids']);
        }
        if (!$existingModel) {
            // 创建新记录
            $param['create_uid']  = $param['member_id'];
            $param['create_time'] = datetime();
            $model = new MemberAccountModel($param);
            $result = $model->save();
        } else {
            // 更新已有记录
            $param['update_uid']  = $param['member_id'];
            if($existingModel['status'] ==1){
                //若审核通过，只修改收货地址
                $param = array(
                    'consignee'=>$param['consignee'],//收货人
                    'phone'=>$param['phone'],//联系电话
                    'region_id'=>$param['region_id'],//收货地址
                    'address'=>$param['address'],//收货详细地址
                );
            }
            $param['update_time'] = datetime();
            $result = $existingModel->save($param);
            $model = $existingModel; // 使用已存在的模型实例
        }

        // 检查保存操作的结果
        if (!$result) {
            exception('保存操作失败');
        }

        $id = $model->$pk;
        if (empty($id)) {
            exception('保存操作失败');
        }

        $param[$pk] = $id;
        MemberAccountCache::del($id);
        return $param;
    }

    /**
     * 买号验号
     * @Author: 易军辉
     * @DateTime:2024-08-08 15:18
     * @param $param
     * @return mixed
     * @throws \think\Exception
     */
    private static function verifyAccount($param)
    {
        $sysSetting = SystemSettingService::info('verify_account_service');
        switch ($sysSetting['verify_account_service']){
            case 1://V兔
                //旺旺验号
                $api_result = VrabbitSdkService::searchPlus($param['accname']);
                if($api_result['code']=='400'){
                    exception($api_result['msg']);
                }else if($api_result['code']=='200'){
                    $api_data = $api_result['data'];
                    //发出好评率%
                    if(array_key_exists('seller_good_rate', $api_data)){
                        $param['issue_comment_tax'] = $api_data['seller_good_rate'];
                    }
                    //性别(直接中文显示：男号/女号/保密)
                    if(array_key_exists('sex', $api_data)){
                        $param['sex'] = $api_data['sex']=='男'?1:($api_data['sex']=='女'?2:0);
                    }
                    //降权数(可能不返回数据)
                    if(array_key_exists('dpower_num', $api_data)){
                        $param['authority'] = $api_data['dpower_num'];
                    }
                    //骗子
                    if(array_key_exists('liar_num', $api_data)){
                        $param['combating_counterfeits'] = $api_data['liar_num'];//打假
                    }
                    //注册时间
                    if(array_key_exists('register_time', $api_data)){
                        $param['register_time'] = $api_data['register_time'];
                    }
                    //收到的好评
                    if(array_key_exists('buyer_good_rate', $api_data)){
                        $param['receive_comment_tax'] = $api_data['buyer_good_rate'];
                    }
                    //中差评数
                    if(array_key_exists('bad_num', $api_data)){
                        $param['bad'] = $api_data['bad_num'];
                    }
                    //淘龄 年为单位
                    if(array_key_exists('tao_age', $api_data)){
                        $param['taoling'] = $api_data['tao_age'];
                    }
                    //买家信誉点
                    if(array_key_exists('buyerGoodNum', $api_data)){
                        $level = self::getLevelValue($api_data['buyerGoodNum']);
                        if($level){
                            $param['level'] =$level ;
                        }
                    }
                    //是否自动审核
                    $memberSetting = MemberSetting::info('is_account_dpower_num');
                    if($memberSetting['is_account_dpower_num']>0 && array_key_exists('dpower_num', $api_data) && $api_data['dpower_num']<=$memberSetting['is_account_dpower_num']){
                        $param['status'] =1;
                        $param['auth_msg'] ='V图验号接口自动审核';
                        $param['auth_time'] =datetime();
                    }
                    $param['is_verify'] =1;//已验号
                    $param['verify_time'] =datetime();//验号时间
                }
                break;
            case 2://淘测测
                $api_result = TaoceSdkService::searchPlus($param['accname']);
                if($api_result['code']=='400'){
                    exception($api_result['msg']);
                }else if($api_result['code']=='200'){
                    $api_data = $api_result['data'];
                    if(isset($api_data['jubaoData'])){
                        $jubaoData = $api_data['jubaoData'];
                        if(array_key_exists('降权', $jubaoData)) {
                            $param['authority'] = $jubaoData['降权'];
                        }
                        if(array_key_exists('差评', $jubaoData)) {
                            $param['bad'] = $jubaoData['差评'];
                        }
                        if(array_key_exists('找茬', $jubaoData)) {
                            $param['find_fault'] = $jubaoData['找茬'];
                        }
                        if(array_key_exists('抽检', $jubaoData)) {
                            $param['spot_check'] = $jubaoData['抽检'];
                        }
                        if(array_key_exists('打假', $jubaoData)) {
                            $param['combating_counterfeits'] = $jubaoData['打假'];
                        }
                        if(array_key_exists('退款', $jubaoData)) {
                            $param['refund'] = $jubaoData['退款'];
                        }
                    }
                    if(isset($api_data['data'])){
                        $data = $api_data['data'];
                        if(array_key_exists('好评率', $data)) {
                            $param['receive_comment_tax'] = $data['好评率'];
                        }
                        if(array_key_exists('淘龄(年)', $data)) {
                            $param['taoling'] = $data['淘龄(年)'];
                        }
                        if(array_key_exists('注册时间', $data)) {
                            $param['register_time'] = $data['注册时间'];
                        }
                        if(array_key_exists('性别', $data)){
                            $param['sex'] = $data['性别']=='男'?1:($data['性别']=='女'?2:0);
                        }
                        if(array_key_exists('淘气值', $data)){
                            $integral = self::extractNumber($data['淘气值']);
                            if($integral){
                                $param['integral'] = $integral;
                            }
                        }
                        if(array_key_exists('安全级别', $data)) {
                            $param['remark'] = $data['安全级别'];
                        }
                    }
                    //是否自动审核
                    $memberSetting = MemberSetting::info('is_account_dpower_num');
                    if($memberSetting['is_account_dpower_num']>0 && array_key_exists('authority', $param) && $param['authority']<=$memberSetting['is_account_dpower_num']){
                        $param['status'] =1;
                        $param['auth_msg'] ='淘测测验号接口自动审核';
                        $param['auth_time'] =datetime();
                    }
                    $param['is_verify'] =1;//已验号
                    $param['verify_time'] =datetime();//验号时间
                }
                break;
        }
        return $param;
    }

    /**
     * 淘气值处理
     * @Author: 易军辉
     * @DateTime:2024-08-08 16:44
     * @param $string
     */
    private static function extractNumber($string)
    {
        if (preg_match('/(\d+)/', $string, $matches)) {
            return $matches[1];
        }
        return null;
    }
    /**
     * 匹配信用等级
     * @Author: 易军辉
     * @DateTime:2024-08-07 21:46
     * @param $string
     * @return mixed|null
     */
    private static function getLevelValue($string)
    {
        // 提取字符串中的数字和关键字部分
        if (preg_match('/(\d+).*?(心|钻|冠)/u', $string, $matches)) {
            $number = $matches[1];
            $keyword = $matches[2];
            // 遍历 LEVEL 常量数组，查找匹配项
            foreach (MemberAccountModel::LEVEL as $level) {
                if ($level['label'] === $number . $keyword) {
                    return $level['value'];
                }
            }
        }
        // 如果没有找到匹配项，返回 null 或其他默认值
        return null;
    }
    /**
     * 根据条件查询账号信息
     * @Author: 易军辉
     * @DateTime:2024-08-06 21:51
     * @param $where 条件
     * @param $field 查询字段
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function infoByWhere($where = [], $field = '')
    {
        $model = new MemberAccountModel();
        if (empty($field)) {
            $field = 'id,title,content,is_order_taking,create_time,update_time,auth_time,register_time,order_taking_time,member_id,store_platform_id,setting_store_type_ids,nickname,accname,level,sex,age,age_index,integral,authority,taoling,evaluate_image_id,last_month_image_id,month_image_id,consignee,phone,region_id,address,status,auth_msg,sort,remark,ip,issue_comment_tax,receive_comment_tax,bad,find_fault,spot_check,refund,combating_counterfeits,serial_num';
        }
        $info = $model->where($where)->field($field)->select();
        if (empty($info)) {
            return [];
        }
        //购物类目
        $info = $info->toArray();
        return $info;
    }

    /**
     * 接单账号开启与关闭
     * @Author: 易军辉
     * @DateTime:2024-08-20 11:19
     * @param $member_id
     * @param $param
     * @return array|mixed
     * @throws \think\Exception
     */
    public static function setOrderTaking($member_id, $param = [])
    {
        $model = new MemberAccountModel();
        $pk = $model->getPk();
        $ids = [];
        foreach ($param['account_list'] as $key=>$val){
            if(isset($val['id']) && array_key_exists('is_order_taking',$val)){
                $res = $model->where('member_id',$member_id)->where($pk, $val['id'])->update([
                    'is_order_taking'=>$val['is_order_taking'],
                    'order_taking_time'=>datetime()
                ]);
                array_push($ids,$val['id']);
            }
        }
        if (count($ids)<=0) {
            exception();
        }
        $param['ids'] = $ids;
        MemberAccountCache::del($ids);
        return $ids;
    }

    /**
     * 根据订单匹配买家
     * @Author: 易军辉
     * @DateTime:2024-08-23 14:48
     * @param $order 订单信息
     * @return mixed
     */
    public static function getAccountByOrder($order)
    {
        /***************************如果是待自选则直接返回***********************************************/
        if($order['status'] == ShopOrderModel::getStatus('o_select',1)){
            if($order['member_id'] && $order['member_account_id']){
                if($order['pending_member_id'] && $order['pending_member_account_id'] && strtotime($order['pending_time'])<=time()){
                    return [];
                }else{
                    return [
                        ['member_id'=>$order['member_id'],'member_account_id'=>$order['member_account_id']]
                    ];
                }
            }
            return [];
        }
        $mer_id = $order['merchant_id']?$order['merchant_id']:0;
        $where_sql = "a.is_disable=0 and a.is_delete=0 and a.status=1 and a.is_order_taking=1 and member.is_disable=0 and member.is_delete=0 and member.is_authentication=1 and member.is_task=1 and member.is_order_taking=1 ";
        /***************************查询商家是否指定买手分组***********************************************/
        $group_list = Db::name('merchant_attributes')->where('mer_id',$mer_id)->field('group_id')->select()->toArray();
        if($group_list){
            $group_ids = implode(',',array_column($group_list,'group_id'));
            $where_sql .="
             -- 查询商家是否指定买手分组
              and member.member_id in(
					SELECT member_a.member_id from ya_member_attributes as member_a where member_a.group_id in(".$group_ids.") GROUP BY member_a.member_id
				) ";
        }

        /***************************买家操作中单数限制***********************************************/
        $setting = SystemSettingService::info('order_member_today_num,order_member_7day_num,order_member_30day_num,order_account_today_num,order_account_7day_num,order_account_30day_num,order_new_member_num,order_new_member_price,order_new_member_30day_num,order_member_conduct_num,order_member_operation_num,order_account_crazy_num,order_account_verify_authority,order_repurchase_type');
        //已接单状态
        $status_str = ShopOrderModel::getStatus('o_delivery',1).","
            .ShopOrderModel::getStatus('o_evaluate',1).","
            .ShopOrderModel::getStatus('o_auth',1).","
            .ShopOrderModel::getStatus('o_success',1);
        //待操作状态
        $operation_status = ShopOrderModel::getStatus('o_listing',1).","
            .ShopOrderModel::getStatus('o_select',1).","
            .ShopOrderModel::getStatus('o_taking',1).","
            .ShopOrderModel::getStatus('o_operation',1);
        //进行中操作状态
        $have_status = ShopOrderModel::getStatus('o_delivery',1).","
            .ShopOrderModel::getStatus('o_evaluate',1).","
            .ShopOrderModel::getStatus('o_auth',1);
        //用户每天限制接单数
        if(isset($setting['order_member_today_num']) && $setting['order_member_today_num']>0){
            $where_sql .= "
             -- 用户每天限制接单数
              and (SELECT COUNT(o.id)
             FROM ya_shop_order AS o
             WHERE o.member_id = a.member_id  and o.is_delete =0 and o.meet_time >= CURDATE() and o.status in (".$status_str.")
              ) < ".$setting['order_member_today_num'];
        }
        //用户近7天限制接单数
        if(isset($setting['order_member_7day_num']) && $setting['order_member_7day_num']>0){
            $where_sql .= "
             -- 用户近7天限制接单数
              and (SELECT COUNT(o.id)
             FROM ya_shop_order AS o
             WHERE o.member_id = a.member_id  and o.is_delete =0 and o.meet_time >= NOW() - INTERVAL 7 DAY  and o.status in (".$status_str.")
              ) < ".$setting['order_member_7day_num'];
        }
        //用户近30天限制接单数
        if(isset($setting['order_member_30day_num']) && $setting['order_member_30day_num']>0){
            $where_sql .= "
             -- 用户近30天限制接单数
              and (SELECT COUNT(o.id)
             FROM ya_shop_order AS o
             WHERE o.member_id = a.member_id  and o.is_delete =0 and o.meet_time >= NOW() - INTERVAL 30 DAY  and o.status in (".$status_str.")
              ) < ".$setting['order_member_30day_num'];
        }
        //用户进行中单数限制
        if(isset($setting['order_member_conduct_num']) && $setting['order_member_conduct_num']>0){
            $where_sql .= "
             -- 用户进行中单数限制
              and (SELECT COUNT(o.id)
             FROM ya_shop_order AS o
             WHERE o.member_id = a.member_id  and o.is_delete =0 and o.status in (".$have_status.")
              ) < ".$setting['order_member_conduct_num'];
        }
        //用户操作中单数限制
        if(isset($setting['order_member_operation_num']) && $setting['order_member_operation_num']>0){
            $where_sql .= "
             -- 用户操作中单数限制
              and (SELECT COUNT(o.id)
             FROM ya_shop_order AS o
             WHERE o.member_id = a.member_id  and o.is_delete =0 and o.status in (".$operation_status.")
              ) < ".$setting['order_member_operation_num'];
        }
        /***************************过滤掉待接单的买号***********************************************/
        $where_sql .= "
             -- 过滤掉待接单的买号
              and (SELECT COUNT(o.id)
             FROM ya_shop_order AS o
             WHERE o.pending_member_id =a.member_id  and o.is_delete =0 and o.pending_member_id is not null and pending_time>=NOW() and o.status in (".ShopOrderModel::getStatus('o_select',1).",".ShopOrderModel::getStatus('o_taking',1).")
              ) <= 0 ";

        /***************************店铺复购天数限制***********************************************/
        $repurchase_data = self::getRepurchaseData($mer_id,$order['merchant_shop_id']);
        if($repurchase_data && isset($repurchase_data['repurchase_days']) && $repurchase_data['repurchase_days']>0 && isset($repurchase_data['shop_ids']) && $repurchase_data['shop_ids']){
            $is_purchase = true;
            //检查订单商家是否勾选复购，有复购则复购天数限制失效
            if($order['setting_price_range_ids']){
                $repeat_purchase_before = Db::name('shop_product_increment')
                    ->whereIn('setting_price_range_id',$order['setting_price_range_ids'])
                    ->where('shop_product_id',$order['shop_product_id'])
                    ->where('setting_price_range_code','Repeat_purchase_before')
                    ->value('id');
                if($repeat_purchase_before){
                    $is_purchase = false;
                }
            }
            if($is_purchase){
                $where_sql .= "
             -- 店铺复购天数限制
              and (SELECT COUNT(o.id)
             FROM ya_shop_order AS o
             WHERE ".($setting['order_repurchase_type']==2?"o.member_id = a.member_id":"o.member_account_id = a.id")." and o.merchant_shop_id in(".$repurchase_data['shop_ids'].") and o.merchant_id= ".$mer_id." and o.is_delete =0 and o.meet_time >= NOW() - INTERVAL ".$repurchase_data['repurchase_days']." DAY  and o.status in (".$status_str.")
              ) < 1";
            }
        }
        /***************************接单账号黑名单***********************************************/
        $merchant_blacklist = Db::name('merchant_blacklist')
            ->where('mer_id',$mer_id)
            ->where('is_disable',0)
            ->where('is_delete',0)
            ->field('member_account_id')
            ->group('member_account_id')
            ->select()
            ->toArray();
        if(count($merchant_blacklist)>0){
            $where_sql .="
              -- 接单账号黑名单
              and a.id not in(". implode(',',array_column($merchant_blacklist,'member_account_id')).") ";
        }

        /***************************查询淘宝平台id***********************************************/
        $taobao_ids = SettingStorePlatformModel::getTaobaoIds();
        if(!$taobao_ids){
            $taobao_ids = [0];
        }
        /***************************平台匹配***********************************************/
        $store_platform_ids = $order['store_platform_id'];
        if(in_array($store_platform_ids,$taobao_ids)){
            $store_platform_ids =implode(',',$taobao_ids);
        }
        $where_sql .= "
             -- 平台匹配
              and a.store_platform_id in(".$store_platform_ids.") ";

        $field = '
            -- 统计 用户 总订单数
            (SELECT COUNT(o.id) 
             FROM ya_shop_order AS o 
             WHERE o.member_id = a.member_id  and o.is_delete =0 and o.status in ('.$status_str.') ) AS order_member_total,
             -- 统计 用户 总本金
            (SELECT sum(o.principal) 
             FROM ya_shop_order AS o 
             WHERE o.member_id = a.member_id  and o.is_delete =0 and o.status in ('.$status_str.') ) AS order_member_principal,
             -- 统计 用户30天 内订单数量
            (SELECT COUNT(o.id) 
             FROM ya_shop_order AS o 
             WHERE o.member_id = a.member_id and o.is_delete =0 and o.status in ('.$status_str.')
               AND o.meet_time >= NOW() - INTERVAL 30 DAY) AS order_member_30_total,
            -- 统计 买号 总订单数
            (SELECT COUNT(o.id) 
             FROM ya_shop_order AS o 
             WHERE o.member_account_id = a.id  and o.is_delete =0 and o.status in ('.$status_str.') ) AS order_account_total,
             -- 统计 今日淘宝账号订单数量
            (SELECT COUNT(o.id) 
             FROM ya_shop_order AS o 
             WHERE o.member_account_id = a.id and a.store_platform_id in('.implode(',',$taobao_ids).') and o.is_delete =0 and o.status in ('.$status_str.')
               AND o.meet_time >= CURDATE()) AS order_account_today_num,
             -- 统计 近7日淘宝账号订单数量
            (SELECT COUNT(o.id) 
             FROM ya_shop_order AS o 
             WHERE o.member_account_id = a.id and a.store_platform_id in('.implode(',',$taobao_ids).') and o.is_delete =0 and o.status in ('.$status_str.')
               AND o.meet_time >= NOW() - INTERVAL 7 DAY ) AS order_account_7day_num,
             -- 统计 近30日淘宝账号订单数量
            (SELECT COUNT(o.id) 
             FROM ya_shop_order AS o 
             WHERE o.member_account_id = a.id and a.store_platform_id in('.implode(',',$taobao_ids).') and o.is_delete =0 and o.status in ('.$status_str.')
               AND o.meet_time >= NOW() - INTERVAL 30 DAY ) AS order_account_30day_num,
             -- 统计 近30日买号订单数量
            (SELECT COUNT(o.id) 
             FROM ya_shop_order AS o 
             WHERE o.member_account_id = a.id  and o.is_delete =0 and o.status in ('.$status_str.')
               AND o.meet_time >= NOW() - INTERVAL 30 DAY ) AS order_account_30_day_num,
            a.id,a.member_id,a.is_member,a.age_index,a.sex,a.level,a.integral,a.region_id,a.authority,a.is_verify,member.create_time as member_create_time';
        $sql = <<<SQL
                SELECT 
                 $field
                FROM ya_member_account AS a
                -- 关联店铺平台
                -- LEFT JOIN ya_setting_store_platform AS platform ON a.store_platform_id = platform.id
                -- 关联买手	
                LEFT JOIN ya_member AS member ON a.member_id = member.member_id
            WHERE
                {$where_sql}
            ORDER BY 
                a.order_taking_time asc
            SQL;
//        echo $sql;exit();
        $list = Db::query($sql);
        $account_list = [];
        $price_condition_list = [];
        /***************************查询增值条件***********************************************/
        if(count($list)>0){
            $range_codes =SettingPriceRangeModel::RANGE_CODES;
            $price_condition_list= self::getPriceCondition($order,$range_codes);
        }
        foreach ($list as $key=>$val){
            //淘宝账号每天限制接单数
            if(isset($setting['order_account_today_num']) && $setting['order_account_today_num']>0 && $val['order_account_today_num']>=$setting['order_account_today_num']){
//                Log::write($val['id'].'：淘宝账号每天限制接单数');
                continue;
            }
            //淘宝账号近7天限制接单数
            if(isset($setting['order_account_7day_num']) && $setting['order_account_7day_num']>0 && $val['order_account_7day_num']>=$setting['order_account_7day_num']){
//                Log::write($val['id'].'：淘宝账号近7天限制接单数');
                continue;
            }
            //淘宝账号近30天限制接单数
            if(isset($setting['order_account_30day_num']) && $setting['order_account_30day_num']>0 && $val['order_account_30day_num']>=$setting['order_account_30day_num']){
//                Log::write($val['id'].'：淘宝账号近30天限制接单数');
                continue;
            }
            //新手限制
            $member_day = self::returnDay($val['member_create_time']);
            if(isset($setting['order_new_member_num']) && $setting['order_new_member_num']>0 && $member_day<=$setting['order_new_member_num']){
                //新手前几单接单限制金额
                if(isset($setting['order_new_member_price']) && $setting['order_new_member_price']>0 && $val['order_member_principal']>$setting['order_new_member_price']){
//                    Log::write($val['id'].'：新手前几单接单限制金额');
                    continue;
                }
                //新手前30天限制接单数
                if(isset($setting['order_new_member_30day_num']) && $setting['order_new_member_30day_num']>0 && $val['order_member_total']>$setting['order_new_member_30day_num']){
//                    Log::write($val['id'].'：新手前30天限制接单数');
                    continue;
                }
            }
            /***************************增值条件过滤***********************************************/
            $is_price_condition = false;
            foreach ($price_condition_list as $pcl_key=>$pcl_val){
                $condition_value = json_decode($pcl_val['condition_value'], true);
                $filed_name = 'price_range_'.$pcl_val['setting_price_range_id']."_".$pcl_val['setting_price_condition_type'];
                switch ($pcl_val['setting_price_range_code']){
                    case $range_codes[0]://年龄限制
                        if(array_key_exists($filed_name, $condition_value) &&  $val['age_index']!=$condition_value[$filed_name]){
//                            Log::write($val['id'].'：年龄限制');
                            $is_price_condition = true;
                        }
                        break;
                    case $range_codes[1]://禁止狂刷号
                        if($val['order_account_30_day_num']>$setting['order_account_crazy_num']){
//                            Log::write($val['id'].'：禁止狂刷号');
                            $is_price_condition = true;
                        }
                        break;
                    case $range_codes[2]://性别限制
                        if(array_key_exists($filed_name, $condition_value)){
                            $spc_labels = explode(',',$pcl_val['spc_label']);
                            $spc_values = explode(',',$pcl_val['spc_value']);
                            $sex = $val['sex']==1?'男':($val['sex']==2?'女':'保密');
                            if(array_search($condition_value[$filed_name], $spc_values) === false || $spc_labels[array_search($condition_value[$filed_name], $spc_values)]!=$sex){
//                                Log::write($val['id'].'：性别限制');
                                $is_price_condition = true;
                            }
                        }
                        break;
                    case $range_codes[3]://帐号等级限制
                        if(array_key_exists($filed_name, $condition_value)){
                            $spc_labels = explode(',',$pcl_val['spc_label']);
                            $spc_values = explode(',',$pcl_val['spc_value']);
                            $spc_index = array_search($condition_value[$filed_name], $spc_values);
                            $level_value = self::getLevelValue($spc_labels[$spc_index]);
                            if($level_value==null){
                                $level_value = 0;
                            }
                            if($spc_index === false || $val['level']<$level_value){
//                                Log::write($val['id'].'：帐号等级限制');
                                $is_price_condition = true;
                            }
                        }
                        break;
                    case $range_codes[4]://淘气值限制
                        if(array_key_exists($filed_name, $condition_value)){
                            $spc_labels = explode(',',$pcl_val['spc_label']);
                            $spc_values = explode(',',$pcl_val['spc_value']);
                            $spc_index = array_search($condition_value[$filed_name], $spc_values);
                            $integral =0;
                            if (preg_match('/\d+(\.\d+)?/', $spc_labels[$spc_index], $matches)) {
                                $integral = $matches[0];
                            }
                            if($spc_index === false || $val['integral']<$integral){
//                                Log::write($val['id'].'：淘气值限制');
                                $is_price_condition = true;
                            }
                        }
                        break;
                    case $range_codes[5]://地区限制
                        if(array_key_exists($filed_name, $condition_value)){
                            $spc_labels = explode(',',$pcl_val['spc_label']);
                            $spc_values = explode(',',$pcl_val['spc_value']);
                            $cv_values = $condition_value[$filed_name];
                            $regions = [];
                            foreach ($spc_values as $spcv_key=>$pscv_val){
                                if(in_array($pscv_val,$cv_values)){
                                    array_push($regions,$spc_labels[$spcv_key]);
                                }
                            }
                            $region_path = Db::name('setting_region')->where('region_id',$val['region_id'])->value('region_path');
                            $region_path = explode(',',$region_path);
                            $region_intersect = array_intersect($regions,$region_path);
                            if(!$region_intersect || count($region_intersect)<=0){
//                                Log::write($val['id'].'：地区限制');
                                $is_price_condition = true;
                            }
                        }
                        break;
                    case $range_codes[6]://复购只允许之前做过
                        $repeat_num = Db::name('shop_order')
                            ->where('is_delete',0)
                            ->where('merchant_id',$order['merchant_id'])
                            ->where('merchant_shop_id',$order['merchant_shop_id'])
                            ->where('member_id',$val['member_id'])
                            ->where('member_account_id',$val['id'])
                            ->whereIn('status',$status_str)
                            ->count();
                        if($repeat_num<=0){
//                            Log::write($val['id'].'：复购只允许之前做过');
                            $is_price_condition = true;
                        }
                        break;
                    case $range_codes[7]://仅限做过商品浏览单的可接,请谨慎勾选
                        $third_ids = Db::name('shop_product_goods')->where('shop_product_id',$order['shop_product_id'])->column('third_id');
                        $llrw_num = Db::name('shop_product_goods')->alias('a')
                            ->leftJoin('shop_order','shop_order.shop_product_id = a.shop_product_id')
                            ->where('shop_order.is_delete',0)
                            ->where('shop_order.merchant_id',$order['merchant_id'])
                            ->where('shop_order.member_id',$val['member_id'])
                            ->where('shop_order.member_account_id',$val['id'])
                            ->where('shop_order.shop_product_type_code',ShopProductTypeModel::LLRW)
                            ->whereIn('shop_order.status',$status_str)
                            ->whereIn('a.third_id',$third_ids)
                            ->count();
                        if($llrw_num<=0){
//                            Log::write($val['id'].'：仅限做过商品浏览单的可接,请谨慎勾选');
                            $is_price_condition = true;
                        }
                        break;
                    case $range_codes[8]://旺旺照妖镜验号
                        if($val['is_verify'] != 1 || $val['authority'] === null || $val['authority']>$setting['order_account_verify_authority']){
//                            Log::write($val['id'].'：旺旺照妖镜验号');
                            $is_price_condition = true;
                        }
                        break;
                    case $range_codes[9]://88会员
                        if($val['is_member'] != 1){
//                            Log::write($val['id'].'：88会员');
                            $is_price_condition = true;
                        }
                        break;
                }
                if($is_price_condition){
                    break;
                }
            }
            if($is_price_condition){
                continue;
            }
            //接单号近一月内狂刷限制单数
            array_push($account_list,[
                'member_id'=>$val['member_id'],
                'member_account_id'=>$val['id'],
            ]);
        }
        return $account_list;
    }

    /**
     * 查询店铺复购天数限制
     * @Author: 易军辉
     * @DateTime:2024-10-10 11:04
     * @param $merchant_id 商家ID
     * @param $merchant_shop_id 店铺ID
     * @return mixed
     */
    private static function getRepurchaseData($merchant_id,$merchant_shop_id)
    {
        $repurchase_sql = <<<SQL
            SELECT 
                a.id,
                a.title,
                a.repurchase_days,
                shop_group.repurchase_days as group_repurchase_days,
                GROUP_CONCAT(b.id) as same_group_shop_ids
            FROM 
                ya_merchant_shop as a
            LEFT JOIN 
                ya_merchant_shop_group as shop_group 
                ON a.shop_group_id = shop_group.id
                    AND shop_group.is_delete = 0 
                AND shop_group.is_disable = 0
            LEFT JOIN 
                ya_merchant_shop as b 
                ON a.shop_group_id = b.shop_group_id 
                    AND a.merchant_id = b.merchant_id
                    AND a.id <> b.id
                AND b.is_delete = 0 
                AND b.is_disable = 0
            WHERE 
                a.merchant_id = {$merchant_id} 
                AND a.id = {$merchant_shop_id} 
                AND a.is_delete = 0 
                AND a.is_disable = 0
            GROUP BY 
                a.id, a.title, a.repurchase_days, shop_group.repurchase_days;
            SQL;

        $list = Db::query($repurchase_sql);
        if(count($list)>0){
            $repurchase_days = $list[0]['group_repurchase_days'];
            if(empty($repurchase_days) || $repurchase_days<=0){
                $repurchase_days = $list[0]['repurchase_days'];
            }
            $shop_ids = $list[0]['same_group_shop_ids'];
            if($shop_ids){
                $shop_ids .=",".$list[0]['id'];
            }else{
                $shop_ids =$list[0]['id'];
            }
            $data = [
                'repurchase_days'=>$repurchase_days,
                'shop_ids'=>$shop_ids
            ];
            return $data;
        }else{
            return false;
        }
    }

    /**
     * 根据用户id查找订单
     * @Author: 易军辉
     * @DateTime:2024-10-08 20:33
     * @param $member_id 买家id
     * @param $member_account_id 买号id
     * @param $type 查询方式：1、系统派单模式 2、买家抢单
     */
    public static function getOrderByAccount($member_id,$member_account_id=null,$type=1)
    {
        $where_sql = "a.member_id =".$member_id." and a.is_disable=0 and a.is_delete=0 and a.status=1 and a.is_order_taking=1 and member.is_disable=0 and member.is_delete=0 and member.is_authentication=1 and member.is_task=1 and member.is_order_taking=1 ";
        if($type==1 && $member_account_id){
            $where_sql .=" and a.id=".$member_account_id;
        }
        /***************************买家操作中单数限制***********************************************/
        $setting = SystemSettingService::info('order_member_today_num,order_member_7day_num,order_member_30day_num,order_account_today_num,order_account_7day_num,order_account_30day_num,order_new_member_num,order_new_member_price,order_new_member_30day_num,order_member_conduct_num,order_member_operation_num,order_account_crazy_num,order_account_verify_authority,order_repurchase_type');
        //已接单状态
        $status_str = ShopOrderModel::getStatus('o_delivery',1).","
            .ShopOrderModel::getStatus('o_evaluate',1).","
            .ShopOrderModel::getStatus('o_auth',1).","
            .ShopOrderModel::getStatus('o_success',1);
        //待操作状态
        $operation_status = ShopOrderModel::getStatus('o_listing',1).","
            .ShopOrderModel::getStatus('o_select',1).","
            .ShopOrderModel::getStatus('o_taking',1).","
            .ShopOrderModel::getStatus('o_operation',1);
        //进行中操作状态
        $have_status = ShopOrderModel::getStatus('o_delivery',1).","
            .ShopOrderModel::getStatus('o_evaluate',1).","
            .ShopOrderModel::getStatus('o_auth',1);
        //用户每天限制接单数
        if(isset($setting['order_member_today_num']) && $setting['order_member_today_num']>0){
            $where_sql .= "
             -- 用户每天限制接单数
              and (SELECT COUNT(o.id)
             FROM ya_shop_order AS o
             WHERE o.member_id = a.member_id  and o.is_delete =0 and o.meet_time >= CURDATE() and o.status in (".$status_str.")
              ) < ".$setting['order_member_today_num'];
        }
        //用户近7天限制接单数
        if(isset($setting['order_member_7day_num']) && $setting['order_member_7day_num']>0){
            $where_sql .= "
             -- 用户近7天限制接单数
              and (SELECT COUNT(o.id)
             FROM ya_shop_order AS o
             WHERE o.member_id = a.member_id  and o.is_delete =0 and o.meet_time >= NOW() - INTERVAL 7 DAY  and o.status in (".$status_str.")
              ) < ".$setting['order_member_7day_num'];
        }
        //用户近30天限制接单数
        if(isset($setting['order_member_30day_num']) && $setting['order_member_30day_num']>0){
            $where_sql .= "
             -- 用户近30天限制接单数
              and (SELECT COUNT(o.id)
             FROM ya_shop_order AS o
             WHERE o.member_id = a.member_id  and o.is_delete =0 and o.meet_time >= NOW() - INTERVAL 30 DAY  and o.status in (".$status_str.")
              ) < ".$setting['order_member_30day_num'];
        }
        //用户进行中单数限制
        if(isset($setting['order_member_conduct_num']) && $setting['order_member_conduct_num']>0){
            $where_sql .= "
             -- 用户进行中单数限制
              and (SELECT COUNT(o.id)
             FROM ya_shop_order AS o
             WHERE o.member_id = a.member_id  and o.is_delete =0 and o.status in (".$have_status.")
              ) < ".$setting['order_member_conduct_num'];
        }
        //用户操作中单数限制
        if(isset($setting['order_member_operation_num']) && $setting['order_member_operation_num']>0){
            $where_sql .= "
             -- 用户操作中单数限制
              and (SELECT COUNT(o.id)
             FROM ya_shop_order AS o
             WHERE o.member_id = a.member_id  and o.is_delete =0 and o.status in (".$operation_status.")
              ) < ".$setting['order_member_operation_num'];
        }
        /***************************过滤掉待接单的买号***********************************************/
        $where_sql .= "
             -- 过滤掉待接单的买号
              and (SELECT COUNT(o.id)
             FROM ya_shop_order AS o
             WHERE o.pending_member_id =a.member_id  and o.is_delete =0 and o.pending_member_id is not null and pending_time>=NOW() and o.status in (".ShopOrderModel::getStatus('o_select',1).",".ShopOrderModel::getStatus('o_taking',1).")
              ) <= 0 ";

        /***************************查询淘宝平台id***********************************************/
        $taobao_ids = SettingStorePlatformModel::getTaobaoIds();
        if(!$taobao_ids){
            $taobao_ids = [0];
        }

        $field = '
            -- 统计 用户 总订单数
            (SELECT COUNT(o.id) 
             FROM ya_shop_order AS o 
             WHERE o.member_id = a.member_id  and o.is_delete =0 and o.status in ('.$status_str.') ) AS order_member_total,
             -- 统计 用户 总本金
            (SELECT sum(o.principal) 
             FROM ya_shop_order AS o 
             WHERE o.member_id = a.member_id  and o.is_delete =0 and o.status in ('.$status_str.') ) AS order_member_principal,
             -- 统计 用户30天 内订单数量
            (SELECT COUNT(o.id) 
             FROM ya_shop_order AS o 
             WHERE o.member_id = a.member_id and o.is_delete =0 and o.status in ('.$status_str.')
               AND o.meet_time >= NOW() - INTERVAL 30 DAY) AS order_member_30_total,
            -- 统计 买号 总订单数
            (SELECT COUNT(o.id) 
             FROM ya_shop_order AS o 
             WHERE o.member_account_id = a.id  and o.is_delete =0 and o.status in ('.$status_str.') ) AS order_account_total,
             -- 统计 今日淘宝账号订单数量
            (SELECT COUNT(o.id) 
             FROM ya_shop_order AS o 
             WHERE o.member_account_id = a.id and a.store_platform_id in('.implode(',',$taobao_ids).') and o.is_delete =0 and o.status in ('.$status_str.')
               AND o.meet_time >= CURDATE()) AS order_account_today_num,
             -- 统计 近7日淘宝账号订单数量
            (SELECT COUNT(o.id) 
             FROM ya_shop_order AS o 
             WHERE o.member_account_id = a.id and a.store_platform_id in('.implode(',',$taobao_ids).') and o.is_delete =0 and o.status in ('.$status_str.')
               AND o.meet_time >= NOW() - INTERVAL 7 DAY ) AS order_account_7day_num,
             -- 统计 近30日淘宝账号订单数量
            (SELECT COUNT(o.id) 
             FROM ya_shop_order AS o 
             WHERE o.member_account_id = a.id and a.store_platform_id in('.implode(',',$taobao_ids).') and o.is_delete =0 and o.status in ('.$status_str.')
               AND o.meet_time >= NOW() - INTERVAL 30 DAY ) AS order_account_30day_num,
             -- 统计 近30日买号订单数量
            (SELECT COUNT(o.id) 
             FROM ya_shop_order AS o 
             WHERE o.member_account_id = a.id  and o.is_delete =0 and o.status in ('.$status_str.')
               AND o.meet_time >= NOW() - INTERVAL 30 DAY ) AS order_account_30_day_num,
            a.id,a.member_id,a.is_member,a.age_index,a.sex,a.level,a.integral,a.region_id,a.authority,a.is_verify,a.store_platform_id,a.create_time as member_create_time ';
        $sql = <<<SQL
                SELECT 
                 $field
                FROM ya_member_account AS a
                -- 关联买手	
                LEFT JOIN ya_member AS member ON a.member_id = member.member_id
            WHERE
                {$where_sql}
            ORDER BY 
                a.order_taking_time asc
            SQL;
        $list = Db::query($sql);
        $account_list = [];//符合接单条件的账号
        foreach ($list as $key=>$val) {
            //淘宝账号每天限制接单数
            if (isset($setting['order_account_today_num']) && $setting['order_account_today_num'] > 0 && $val['order_account_today_num'] >= $setting['order_account_today_num']) {
                continue;
            }
            //淘宝账号近7天限制接单数
            if (isset($setting['order_account_7day_num']) && $setting['order_account_7day_num'] > 0 && $val['order_account_7day_num'] >= $setting['order_account_7day_num']) {
                continue;
            }
            //淘宝账号近30天限制接单数
            if (isset($setting['order_account_30day_num']) && $setting['order_account_30day_num'] > 0 && $val['order_account_30day_num'] >= $setting['order_account_30day_num']) {
                continue;
            }
            //新手限制
            $member_day = self::returnDay($val['member_create_time']);
            if (isset($setting['order_new_member_num']) && $setting['order_new_member_num'] > 0 && $member_day <= $setting['order_new_member_num']) {
                //新手前几单接单限制金额
                if (isset($setting['order_new_member_price']) && $setting['order_new_member_price'] > 0 && $val['order_member_principal'] > $setting['order_new_member_price']) {
                    continue;
                }
                //新手前30天限制接单数
                if (isset($setting['order_new_member_30day_num']) && $setting['order_new_member_30day_num'] > 0 && $val['order_member_total'] > $setting['order_new_member_30day_num']) {
                    continue;
                }
            }
            array_push($account_list,$val);
        }
        if($account_list){
            /***************************平台匹配***********************************************/
            $store_platform_ids  = array_unique(array_column($account_list,'store_platform_id'));
            $store_platform_ids =self::updateArray($store_platform_ids,$taobao_ids);
            $order_where = " and a.store_platform_id in (".implode(',',$store_platform_ids).")";
            /***************************查询买手是否指定分组***********************************************/
            $merchant_ids = Db::query("SELECT mer_id from ya_merchant_attributes where group_id in(
                                            SELECT group_id from ya_member_attributes where member_id = ".$member_id."
                                        ) GROUP BY mer_id");
            if($merchant_ids){
                $order_where .=" and a.merchant_id in (".implode(',',array_column($merchant_ids,'mer_id')).")";
            }
            /***************************接单账号黑名单***********************************************/
            //等待接单条件中使用
            $merchant_blacklist = Db::name('merchant_blacklist')
                ->where('member_id',$member_id)
                ->whereIn('member_account_id',array_column($account_list,'member_account_id'))
                ->where('is_disable',0)
                ->where('is_delete',0)
                ->field('mer_id')
                ->group('mer_id')
                ->select()
                ->toArray();
            if($merchant_blacklist){
                $order_where .=" and a.merchant_id not in (".implode(',',array_column($merchant_blacklist,'mer_id')).")";
            }
            /***************************订单查询***********************************************/
            $member_setting = MemberSetting::info('order_effective_time');
            if(!isset($member_setting['order_effective_time']) || $member_setting['order_effective_time']<=0){
                $member_setting['order_effective_time'] = 60*60*24;//若没有设置，则默认一天
            }else{
//                $member_setting['order_effective_time'] +=10;//加10秒损耗时间
            }
            $o_select = ShopOrderModel::getStatus('o_select',1);//待自选
            $member_ids = implode(',',array_unique(array_column($account_list,'member_id')));
            $member_account_ids = implode(',',array_unique(array_column($account_list,'id')));
            $o_taking = ShopOrderModel::getStatus('o_taking',1);//待接单
            $ptbt = ShopProductTypeModel::PTBT;
            $time = date('Y-m-d H:i:s');
            $order_sql = <<<SQL
                SELECT * from ya_shop_order as a
                where 
                (a.status = {$o_taking} 
                or (a.status = {$o_select} and a.pending_member_id in({$member_ids}) and a.pending_member_account_id in({$member_account_ids})))
                and a.shop_product_type_code <> '{$ptbt}'
                and (a.pending_time is null or a.pending_time < '{$time}')
                {$order_where}
                order by a.status asc
            SQL;
//            echo $order_sql;exit();
            $order_list = Db::query($order_sql);
            $order_data = [];
            $range_codes =SettingPriceRangeModel::RANGE_CODES;
            /***************************通过账号过滤订单***********************************************/
            foreach ($order_list as $o_key=>$order){
                /***************************店铺复购天数限制***********************************************/
                $repurchase_data = self::getRepurchaseData($order['merchant_id'],$order['merchant_shop_id']);
                $is_purchase = false;
                if($repurchase_data && isset($repurchase_data['repurchase_days']) && $repurchase_data['repurchase_days']>0 && isset($repurchase_data['shop_ids']) && $repurchase_data['shop_ids']){
                    $is_purchase = true;
                }
                /***************************增值条件过滤***********************************************/
                $price_condition_list= self::getPriceCondition($order,$range_codes);
                $is_price_condition = false;
                foreach ($account_list as $key=>$val){
                    if($val['store_platform_id'] == $order['store_platform_id']){
                        foreach ($price_condition_list as $pcl_key=>$pcl_val){
                            $condition_value = json_decode($pcl_val['condition_value'], true);
                            $filed_name = 'price_range_'.$pcl_val['setting_price_range_id']."_".$pcl_val['setting_price_condition_type'];
                            switch ($pcl_val['setting_price_range_code']){
                                case $range_codes[0]://年龄限制
                                    if(array_key_exists($filed_name, $condition_value) &&  $val['age_index']!=$condition_value[$filed_name]){
                                        $is_price_condition = true;
                                    }
                                    break;
                                case $range_codes[1]://禁止狂刷号
                                    if($val['order_account_30_day_num']>$setting['order_account_crazy_num']){
                                        $is_price_condition = true;
                                    }
                                    break;
                                case $range_codes[2]://性别限制
                                    if(array_key_exists($filed_name, $condition_value)){
                                        $spc_labels = explode(',',$pcl_val['spc_label']);
                                        $spc_values = explode(',',$pcl_val['spc_value']);
                                        $sex = $val['sex']==1?'男':($val['sex']==2?'女':'保密');
                                        if(array_search($condition_value[$filed_name], $spc_values) === false || $spc_labels[array_search($condition_value[$filed_name], $spc_values)]!=$sex){
                                            $is_price_condition = true;
                                        }
                                    }
                                    break;
                                case $range_codes[3]://帐号等级限制
                                    if(array_key_exists($filed_name, $condition_value)){
                                        $spc_labels = explode(',',$pcl_val['spc_label']);
                                        $spc_values = explode(',',$pcl_val['spc_value']);
                                        $spc_index = array_search($condition_value[$filed_name], $spc_values);
                                        $level_value = self::getLevelValue($spc_labels[$spc_index]);
                                        if($level_value==null){
                                            $level_value = 0;
                                        }
                                        if($spc_index === false || $val['level']<$level_value){
                                            $is_price_condition = true;
                                        }
                                    }
                                    break;
                                case $range_codes[4]://淘气值限制
                                    if(array_key_exists($filed_name, $condition_value)){
                                        $spc_labels = explode(',',$pcl_val['spc_label']);
                                        $spc_values = explode(',',$pcl_val['spc_value']);
                                        $spc_index = array_search($condition_value[$filed_name], $spc_values);
                                        $integral =0;
                                        if (preg_match('/\d+(\.\d+)?/', $spc_labels[$spc_index], $matches)) {
                                            $integral = $matches[0];
                                        }
                                        if($spc_index === false || $val['integral']<$integral){
                                            $is_price_condition = true;
                                        }
                                    }
                                    break;
                                case $range_codes[5]://地区限制
                                    if(array_key_exists($filed_name, $condition_value)){
                                        $spc_labels = explode(',',$pcl_val['spc_label']);
                                        $spc_values = explode(',',$pcl_val['spc_value']);
                                        $cv_values = $condition_value[$filed_name];
                                        $regions = [];
                                        foreach ($spc_values as $spcv_key=>$pscv_val){
                                            if(in_array($pscv_val,$cv_values)){
                                                array_push($regions,$spc_labels[$spcv_key]);
                                            }
                                        }
                                        $region_path = Db::name('setting_region')->where('region_id',$val['region_id'])->value('region_path');
                                        $region_path = explode(',',$region_path);
                                        $region_intersect = array_intersect($regions,$region_path);
                                        if(!$region_intersect || count($region_intersect)<=0){
                                            $is_price_condition = true;
                                        }
                                    }
                                    break;
                                case $range_codes[6]://复购只允许之前做过
                                    //检查订单商家是否勾选复购，有复购则复购天数限制失效
                                    $is_purchase = false;
                                    //查询复购数量
                                    $repeat_num = Db::name('shop_order')
                                        ->where('is_delete',0)
                                        ->where('merchant_id',$order['merchant_id'])
                                        ->where('merchant_shop_id',$order['merchant_shop_id'])
                                        ->where('member_id',$val['member_id'])
                                        ->where('member_account_id',$val['id'])
                                        ->whereIn('status',$status_str)
                                        ->count();
                                    if($repeat_num<=0){
                                        $is_price_condition = true;
                                    }
                                    break;
                                case $range_codes[7]://仅限做过商品浏览单的可接,请谨慎勾选
                                    $third_ids = Db::name('shop_product_goods')->where('shop_product_id',$order['shop_product_id'])->column('third_id');
                                    $llrw_num = Db::name('shop_product_goods')->alias('a')
                                        ->leftJoin('shop_order','shop_order.shop_product_id = a.shop_product_id')
                                        ->where('shop_order.is_delete',0)
                                        ->where('shop_order.merchant_id',$order['merchant_id'])
                                        ->where('shop_order.member_id',$val['member_id'])
                                        ->where('shop_order.member_account_id',$val['id'])
                                        ->where('shop_order.shop_product_type_code',ShopProductTypeModel::LLRW)
                                        ->whereIn('shop_order.status',$status_str)
                                        ->whereIn('a.third_id',$third_ids)
                                        ->count();
                                    if($llrw_num<=0){
//                                        Log::write($val['id'].'：仅限做过商品浏览单的可接,请谨慎勾选');
                                        $is_price_condition = true;
                                    }
                                    break;
                                case $range_codes[8]://旺旺照妖镜验号
                                    if($val['is_verify'] != 1 || $val['authority'] === null || $val['authority']>$setting['order_account_verify_authority']){
                                        $is_price_condition = true;
                                    }
                                    break;
                                case $range_codes[9]://88会员
                                    if($val['is_member'] != 1){
                                        $is_price_condition = true;
                                    }
                                    break;
                            }
                            if($is_price_condition){
                                break;
                            }
                        }
                        //查询买号或者买家是否达到店铺复购限制
                        if($is_purchase){
                            $purchase_num = Db::name('shop_order')
                                ->where('is_delete',0)
                                ->where('merchant_id',$order['merchant_id'])
                                ->where('merchant_shop_id',$order['merchant_shop_id'])
                                ->when(true,function ($query)use($setting,$val){
                                    if($setting['order_repurchase_type']==2){
                                        $query->where('member_id',$val['member_id']);
                                    }else{
                                        $query->where('member_account_id',$val['id']);
                                    }
                                })
                                ->where('meet_time','>=',date('Y-m-d H:i:s', strtotime('-'.$repurchase_data['repurchase_days'].' days')))
                                ->whereIn('status',$status_str)
                                ->count();
                            if($purchase_num>0 && $setting['order_repurchase_type']==2){
                                $is_price_condition = true;
                                break;
                            }else if($purchase_num>0){
                                $is_price_condition = true;
                                continue;
                            }
                        }
                        //当该买号适合接该订单
                        if(!$is_price_condition){
                            $order['pending_member_id'] = $val['member_id'];
                            $order['pending_member_account_id'] = $val['id'];
                            $order['pending_time'] = date('Y-m-d H:i:s', (time()+$member_setting['order_effective_time']));
                            break;
                        }
                    }
                }
                if($is_price_condition){
                    continue;
                }else if($order['pending_member_id'] && $order['pending_member_account_id'] && $order['pending_time']){
                    array_push($order_data,$order);
                    if($type==1){
                        $res = Db::name('shop_order')
                            ->where('id',$order['id'])
                            ->update([
                                'pending_member_id'=>$order['pending_member_id'],
                                'pending_member_account_id'=>$order['pending_member_account_id'],
                                'pending_time'=>$order['pending_time'],
                            ]);
                        //通知用户有待接订单
                        CacheRedisService::set('OrderAssignListener_'.$member_id,$order['id'],$member_setting['order_effective_time']);
                        break;
                    }
                }
            }
            return $order_data;
        }
        return  false;
    }

    /**
     * 处理店铺平台ID
     * @Author: 易军辉
     * @DateTime:2024-10-09 10:00
     * @param $a 账号平台
     * @param $b 淘宝、天猫平台
     */
    private static function updateArray($a, $b) {
        if(count($b)<2){
            return $a;
        }
        // 遍历$b数组，检查$b数组中的两个值是否在$a数组中
        if (in_array($b[0], $a) && !in_array($b[1], $a)) {
            $a[] = $b[1];  // 如果$b[0]在$a中，且$b[1]不在$a中，则添加$b[1]到$a
        } elseif (in_array($b[1], $a) && !in_array($b[0], $a)) {
            $a[] = $b[0];  // 如果$b[1]在$a中，且$b[0]不在$a中，则添加$b[0]到$a
        }
        return $a;
    }
    /**
     * 获取过滤买家的增值条件
     * @Author: 易军辉
     * @DateTime:2024-08-26 17:13
     * @param $order
     * @param $range_codes
     * @return array
     */
    private static function getPriceCondition($order,$range_codes)
    {
        if(!isset($order['setting_price_range_ids']) || !isset($order['shop_product_id']) || !$order['setting_price_range_ids']){
            return [];
        }
        $quoted_range_codes = array_map(function($code) { return "'$code'"; }, $range_codes);
        $range_code_str = implode(',', $quoted_range_codes);
        $sql = <<<SQL
            SELECT spi.setting_price_range_id,spi.setting_price_condition_type,spi.setting_price_range_code,spi.mer_describe,spi.condition_value,GROUP_CONCAT(spc.label) as spc_label,GROUP_CONCAT(spc.`value`) as spc_value
            from ya_shop_product_increment as spi
            LEFT JOIN ya_setting_price_condition as spc on spi.setting_price_range_id=spc.setting_price_range_id
            where spi.setting_price_range_id in({$order['setting_price_range_ids']}) 
              and spi.shop_product_id = {$order['shop_product_id']}
              and spi.setting_price_range_code in({$range_code_str})
            GROUP BY spi.setting_price_range_id
        SQL;
        $list = Db::query($sql);
        return $list;
    }


    /**
     * 查询可接单的用户数
     * @Author: 易军辉
     * @DateTime:2024-08-29 10:53
     * @return int 返回数量
     */
    public static function getWaitAccountNum()
    {
        $where_sql = "a.is_disable=0 and a.is_delete=0 and a.status=1 and a.is_order_taking=1 and member.is_disable=0 and member.is_delete=0 and member.is_authentication=1 and member.is_task=1 and member.is_order_taking=1 ";
        /***************************买家操作中单数限制***********************************************/
        $setting = SystemSettingService::info('order_member_today_num,order_member_7day_num,order_member_30day_num,order_account_today_num,order_account_7day_num,order_account_30day_num,order_new_member_num,order_new_member_price,order_new_member_30day_num,order_member_conduct_num,order_member_operation_num,order_account_crazy_num,order_account_verify_authority');
        //已接单状态
        $status_str = ShopOrderModel::getStatus('o_delivery',1).","
            .ShopOrderModel::getStatus('o_evaluate',1).","
            .ShopOrderModel::getStatus('o_auth',1).","
            .ShopOrderModel::getStatus('o_success',1);
        //待操作状态
        $operation_status = ShopOrderModel::getStatus('o_listing',1).","
            .ShopOrderModel::getStatus('o_select',1).","
            .ShopOrderModel::getStatus('o_taking',1).","
            .ShopOrderModel::getStatus('o_operation',1);
        //进行中操作状态
        $have_status = ShopOrderModel::getStatus('o_delivery',1).","
            .ShopOrderModel::getStatus('o_evaluate',1).","
            .ShopOrderModel::getStatus('o_auth',1);
        //用户每天限制接单数
        if(isset($setting['order_member_today_num']) && $setting['order_member_today_num']>0){
            $where_sql .= "
             -- 用户每天限制接单数
              and (SELECT COUNT(o.id)
             FROM ya_shop_order AS o
             WHERE o.member_id = a.member_id  and o.is_delete =0 and o.meet_time >= CURDATE() and o.status in (".$status_str.")
              ) < ".$setting['order_member_today_num'];
        }
        //用户近7天限制接单数
        if(isset($setting['order_member_7day_num']) && $setting['order_member_7day_num']>0){
            $where_sql .= "
             -- 用户近7天限制接单数
              and (SELECT COUNT(o.id)
             FROM ya_shop_order AS o
             WHERE o.member_id = a.member_id  and o.is_delete =0 and o.meet_time >= NOW() - INTERVAL 7 DAY  and o.status in (".$status_str.")
              ) < ".$setting['order_member_7day_num'];
        }
        //用户近30天限制接单数
        if(isset($setting['order_member_30day_num']) && $setting['order_member_30day_num']>0){
            $where_sql .= "
             -- 用户近30天限制接单数
              and (SELECT COUNT(o.id)
             FROM ya_shop_order AS o
             WHERE o.member_id = a.member_id  and o.is_delete =0 and o.meet_time >= NOW() - INTERVAL 30 DAY  and o.status in (".$status_str.")
              ) < ".$setting['order_member_30day_num'];
        }
        //用户进行中单数限制
        if(isset($setting['order_member_conduct_num']) && $setting['order_member_conduct_num']>0){
            $where_sql .= "
             -- 用户进行中单数限制
              and (SELECT COUNT(o.id)
             FROM ya_shop_order AS o
             WHERE o.member_id = a.member_id  and o.is_delete =0 and o.status in (".$have_status.")
              ) < ".$setting['order_member_conduct_num'];
        }
        //用户操作中单数限制
        if(isset($setting['order_member_operation_num']) && $setting['order_member_operation_num']>0){
            $where_sql .= "
             -- 用户操作中单数限制
              and (SELECT COUNT(o.id)
             FROM ya_shop_order AS o
             WHERE o.member_id = a.member_id  and o.is_delete =0 and o.status in (".$operation_status.")
              ) < ".$setting['order_member_operation_num'];
        }
        /***************************过滤掉待接单的买号***********************************************/
        $where_sql .= "
             -- 过滤掉待接单的买号
              and (SELECT COUNT(o.id)
             FROM ya_shop_order AS o
             WHERE o.pending_member_id =a.member_id  and o.is_delete =0 and o.pending_member_id is not null and pending_time>=NOW() and o.status in (".ShopOrderModel::getStatus('o_select',1).",".ShopOrderModel::getStatus('o_taking',1).")
              ) <= 0 ";
        $sql = <<<SQL
                SELECT  count(a.id) as count
                FROM ya_member_account AS a
                -- 关联买手	
                LEFT JOIN ya_member AS member ON a.member_id = member.member_id
            WHERE
                {$where_sql}
            SQL;
//        echo $sql;exit();
        $list = Db::query($sql);
        if($list){
            return $list[0]['count'];
        }
        return 0;
    }

    /**
     * 买家接单效验
     * @Author: 易军辉
     * @DateTime:2024-10-25 14:28
     * @param $member_id 买家id
     * @param $shop_product_id 商品id
     * @param $type 使用类型：1、平台补贴商品
     * @param $exce 是否提示报错
     * @return true
     */
    public static function getMemberOrderValidation($member_id,$shop_product_id,$type,$exce = true)
    {
        $merchant_id = 0;
        $merchant_shop_id = 0;
        $shop_product_type_code = "";
        //根据商品id查找商家、店铺id
        if($shop_product_id){
            $shop_product = Db::name('shop_product')
                ->where('id',$shop_product_id)
                ->where('is_disable',0)
                ->where('is_delete',0)
                ->field('merchant_id,merchant_shop_id,shop_product_type_code')
                ->find();
            if($shop_product){
                $merchant_id = $shop_product['merchant_id'];
                $merchant_shop_id= $shop_product['merchant_shop_id'];
                $shop_product_type_code= $shop_product['shop_product_type_code'];
            }
        }
        /***********************************************黑名单***********************************************/
        $merchant_blacklist_count = Db::name('merchant_blacklist')
            ->where('mer_id',$merchant_id)
            ->where('member_id',$member_id)
            ->where('is_disable',0)
            ->where('is_delete',0)
            ->count();
        if($merchant_blacklist_count>0 && $exce){
            exception('您被该商家拉黑，请挑选其它商品');
        }

        /***************************买家操作中单数限制***********************************************/
        $setting = SystemSettingService::info('order_member_today_num,order_member_7day_num,order_member_30day_num,order_account_today_num,order_account_7day_num,order_account_30day_num,order_new_member_num,order_new_member_price,order_new_member_30day_num,order_member_conduct_num,order_member_operation_num,order_account_crazy_num,order_account_verify_authority');
        //已接单状态
        $status_str = ShopOrderModel::getStatus('o_delivery',1).","
            .ShopOrderModel::getStatus('o_evaluate',1).","
            .ShopOrderModel::getStatus('o_auth',1).","
            .ShopOrderModel::getStatus('o_success',1);
        //待操作状态
        $operation_status = ShopOrderModel::getStatus('o_listing',1).","
            .ShopOrderModel::getStatus('o_select',1).","
            .ShopOrderModel::getStatus('o_taking',1).","
            .ShopOrderModel::getStatus('o_operation',1);
        //进行中操作状态
        $have_status = ShopOrderModel::getStatus('o_delivery',1).","
            .ShopOrderModel::getStatus('o_evaluate',1).","
            .ShopOrderModel::getStatus('o_auth',1);
        //待接单状态
        $wait_status = ShopOrderModel::getStatus('o_select',1).","
            .ShopOrderModel::getStatus('o_taking',1);
        /***********************************************店铺复购天数限制***********************************************/
        $repurchase_data = self::getRepurchaseData($merchant_id,$merchant_shop_id);
        $repurchase_sql = "";
        if($repurchase_data && isset($repurchase_data['repurchase_days']) && $repurchase_data['repurchase_days']>0 ){
            $repurchase_sql = "
                -- 店铺复购天数限制
                (SELECT COUNT(o.id)
             FROM ya_shop_order AS o
             WHERE o.member_id = a.member_id and o.merchant_shop_id in(".$merchant_shop_id.") and o.merchant_id= ".$merchant_id." and o.is_delete =0 and o.meet_time >= NOW() - INTERVAL ".$repurchase_data['repurchase_days']." DAY  and o.status in (".$status_str.")
              ) as repurchase_order_num,
            ";
        }
        $sql = <<<SQL
            SELECT 
            a.member_id,
            a.username,
            a.create_time,
            {$repurchase_sql}
            -- 用户每天限制接单数
            (SELECT COUNT(o.id)
                         FROM ya_shop_order AS o
                         WHERE o.member_id = a.member_id  and o.is_delete =0 and o.meet_time >= CURDATE() and o.status in ({$status_str})
            ) as order_member_today_num,
            -- 用户近7天限制接单数
            (SELECT COUNT(o.id)
                         FROM ya_shop_order AS o
                         WHERE o.member_id = a.member_id  and o.is_delete =0 and o.meet_time >= NOW() - INTERVAL 7 DAY  and o.status in ({$status_str})
            ) as order_member_7day_num,
            -- 用户近30天限制接单数
            (SELECT COUNT(o.id)
                         FROM ya_shop_order AS o
                         WHERE o.member_id = a.member_id  and o.is_delete =0 and o.meet_time >= NOW() - INTERVAL 30 DAY  and o.status in ({$status_str})
            ) as order_member_30day_num,
            -- 用户进行中单数
            (SELECT COUNT(o.id)
             FROM ya_shop_order AS o
             WHERE o.member_id = a.member_id  and o.is_delete =0 and o.status in ({$have_status})
            ) as order_member_conduct_num,
            -- 用户操作中单数限制
            (SELECT COUNT(o.id)
                 FROM ya_shop_order AS o
                 WHERE o.member_id = a.member_id  and o.is_delete =0 and o.status in ({$operation_status})
            ) as order_member_operation_num,
            -- 统计 用户 总订单数
            (SELECT COUNT(o.id) 
             FROM ya_shop_order AS o 
             WHERE o.member_id = a.member_id  and o.is_delete =0 and o.status in ({$status_str}) 
            ) AS order_member_total,
            -- 统计 用户 总本金
            (SELECT sum(o.principal) 
                 FROM ya_shop_order AS o 
                 WHERE o.member_id = a.member_id  and o.is_delete =0 and o.status in ({$status_str}) 
            ) AS order_member_principal,
            -- 统计 用户 垫付金额
            (SELECT sum(o.advance_amount) 
                 FROM ya_shop_order AS o 
                 WHERE o.member_id = a.member_id  and o.is_delete =0 and o.status in ({$status_str}) 
            ) AS order_member_advance_amount,
            -- 统计 待接单数
            (
                SELECT COUNT(o.id)
                 FROM ya_shop_order AS o
                 WHERE o.pending_member_id =a.member_id  and o.is_delete =0 and o.pending_member_id is not null and pending_time>=NOW() and o.status in ({$wait_status})
            ) as order_member_pending
            from ya_member as a
            where 
            a.member_id = {$member_id}
            and a.is_disable=0
            and a.is_delete = 0
        SQL;
        $list = Db::query($sql);
        if($exce){
            foreach ($list as $key=>$val){

                //店铺复购天数限制
                if(isset($val['repurchase_order_num']) && $val['repurchase_order_num']>0){
                    exception('该店铺下商品限购一件'.($repurchase_data['repurchase_days']?"，请在".$repurchase_data['repurchase_days']."天后再次进行购买":''));
                }
                //用户每天限制接单数
                if (isset($setting['order_member_today_num']) && $setting['order_member_today_num'] > 0 && $val['order_member_today_num'] >= $setting['order_member_today_num']) {
                    exception('对不起，您今日购买件数已到达最高');
                }
                //用户近7天限制接单数
                if (isset($setting['order_member_7day_num']) && $setting['order_member_7day_num'] > 0 && $val['order_member_7day_num'] >= $setting['order_member_7day_num']) {
                    exception('对不起，您本周购买件数已到达最高');
                }
                //用户近30天限制接单数
                if (isset($setting['order_member_30day_num']) && $setting['order_member_30day_num'] > 0 && $val['order_member_30day_num'] >= $setting['order_member_30day_num']) {
                    exception('对不起，您本月购买件数已到达最高');
                }
                //用户进行中单数限制
                if (isset($setting['order_member_conduct_num']) && $setting['order_member_conduct_num'] > 0 && $val['order_member_conduct_num'] >= $setting['order_member_conduct_num']) {
                    exception('对不起，您未完成的订单数已到达最高');
                }
                //用户操作中单数限制
                if (isset($setting['order_member_operation_num']) && $setting['order_member_operation_num'] > 0 && $val['order_member_operation_num'] >= $setting['order_member_operation_num']) {
                    exception('您还有待操作的订单需要处理');
                }
                //待接单数限制
                if(isset($val['order_member_pending']) && $val['order_member_pending']>0){
                    exception('您有待接订单请前往处理');
                }
                //新手期条件限制
                $member_day = self::returnDay($val['create_time']);
                if (isset($setting['order_new_member_num']) && $setting['order_new_member_num'] > 0 && $member_day <= $setting['order_new_member_num']) {
                    $order_member_principal = $val['order_member_principal'];
                    if($shop_product_type_code == 'PTBT'){
                        $order_member_principal = $val['order_member_advance_amount'];
                    }
                    //新手前几单接单限制金额
                    if (isset($setting['order_new_member_price']) && $setting['order_new_member_price'] > 0 && $order_member_principal > $setting['order_new_member_price']) {
                        exception('对不起，您初期购买金额已到达最高');
                    }
                    //新手前30天限制接单数
                    if (isset($setting['order_new_member_30day_num']) && $setting['order_new_member_30day_num'] > 0 && $val['order_member_total'] > $setting['order_new_member_30day_num']) {
                        exception('对不起，您初期购买件数已到达最高');
                    }
                }
            }
        }
        if($type==1){
            return true;
        }else{
            return $list;
        }
    }

    /**
     * 获取距离今日的天数
     * @Author: 易军辉
     * @DateTime:2024-10-25 17:39
     * @param $create_time
     * @return float|int
     * @throws \Exception
     */
    private static function returnDay($create_time)
    {
        $specifiedDate = new DateTime($create_time);
        $currentDate = new DateTime();
        $interval = $currentDate->diff($specifiedDate);
        return abs($interval->days);
    }

    /**
     * 买号抢单效验
     * @Author: 易军辉
     * @DateTime:2024-10-25 14:28
     * @param $member_id 买家id
     * @param $member_account_id 买号id
     * @param $type 来源：1、抢单列表 2、抢单验证
     * @param $shop_order_id 订单id
     * @return true
     */
    public static function getMemberAccountOrderValidation($member_id,$member_account_id,$type=1,$shop_order_id=null)
    {
        $res = [
            'code'=>0,//0、买号问题 1、成功
            'data'=>[],
            'msg'=>'系统繁忙，请稍后再试',
        ];
        /***************************买号条件处理***********************************************/
        $member_where_sql = "";
        if($member_account_id && is_array($member_account_id)){
            $member_where_sql .=" and a.id in(".implode(',',$member_account_id).")";
        }else if($member_account_id && $member_account_id>0){
            $member_where_sql .=" and a.id = ".$member_account_id;
        }
        /***************************买家操作中单数限制***********************************************/
        $setting = SystemSettingService::info('order_member_today_num,order_member_7day_num,order_member_30day_num,order_account_today_num,order_account_7day_num,order_account_30day_num,order_new_member_num,order_new_member_price,order_new_member_30day_num,order_member_conduct_num,order_member_operation_num,order_account_crazy_num,order_account_verify_authority,order_repurchase_type');
        //已接单状态
        $status_str = ShopOrderModel::getStatus('o_delivery',1).","
            .ShopOrderModel::getStatus('o_evaluate',1).","
            .ShopOrderModel::getStatus('o_auth',1).","
            .ShopOrderModel::getStatus('o_success',1);
        //待操作状态
        $operation_status = ShopOrderModel::getStatus('o_listing',1).","
            .ShopOrderModel::getStatus('o_select',1).","
            .ShopOrderModel::getStatus('o_taking',1).","
            .ShopOrderModel::getStatus('o_operation',1);
        //进行中操作状态
        $have_status = ShopOrderModel::getStatus('o_delivery',1).","
            .ShopOrderModel::getStatus('o_evaluate',1).","
            .ShopOrderModel::getStatus('o_auth',1);
        //待接单状态
        $wait_status = ShopOrderModel::getStatus('o_select',1).","
            .ShopOrderModel::getStatus('o_taking',1);
        /***************************查询淘宝平台id***********************************************/
        $taobao_ids = SettingStorePlatformModel::getTaobaoIds();
        if(!$taobao_ids){
            $taobao_ids = [0];
        }
        $taobao_str = implode(',',$taobao_ids);
        $member_sql = <<<SQL
            SELECT 
            member.member_id,
            a.id,
            a.id as member_account_id,
            a.store_platform_id,
            a.is_member,
            a.is_verify,
            a.authority,
            a.age_index,
            a.sex,
            a.level,
            a.integral,
            a.region_id,
            member.username,
            member.create_time,
            -- 用户每天限制接单数
            (SELECT COUNT(o.id)
                         FROM ya_shop_order AS o
                         WHERE o.member_id = member.member_id  and o.is_delete =0 and o.meet_time >= CURDATE() and o.status in ({$status_str})
            ) as order_member_today_num,
            -- 用户近7天限制接单数
            (SELECT COUNT(o.id)
                         FROM ya_shop_order AS o
                         WHERE o.member_id = member.member_id  and o.is_delete =0 and o.meet_time >= NOW() - INTERVAL 7 DAY  and o.status in ({$status_str})
            ) as order_member_7day_num,
            -- 用户近30天限制接单数
            (SELECT COUNT(o.id)
                         FROM ya_shop_order AS o
                         WHERE o.member_id = member.member_id  and o.is_delete =0 and o.meet_time >= NOW() - INTERVAL 30 DAY  and o.status in ({$status_str})
            ) as order_member_30day_num,
            -- 用户进行中单数
            (SELECT COUNT(o.id)
             FROM ya_shop_order AS o
             WHERE o.member_id = member.member_id  and o.is_delete =0 and o.status in ({$have_status})
            ) as order_member_conduct_num,
            -- 用户操作中单数限制
            (SELECT COUNT(o.id)
                 FROM ya_shop_order AS o
                 WHERE o.member_id = member.member_id  and o.is_delete =0 and o.status in ({$operation_status})
            ) as order_member_operation_num,
            -- 统计 用户 总订单数
            (SELECT COUNT(o.id) 
             FROM ya_shop_order AS o 
             WHERE o.member_id = member.member_id  and o.is_delete =0 and o.status in ({$status_str}) 
            ) AS order_member_total,
            -- 统计 用户 总本金
            (SELECT sum(o.principal) 
                 FROM ya_shop_order AS o 
                 WHERE o.member_id = member.member_id  and o.is_delete =0 and o.status in ({$status_str}) 
            ) AS order_member_principal,
            -- 统计 待接单数
            (
                SELECT COUNT(o.id)
                 FROM ya_shop_order AS o
                 WHERE o.pending_member_id =member.member_id  and o.is_delete =0 and o.pending_member_id is not null and pending_time>=NOW() and o.status in ({$wait_status})
            ) as order_member_pending,
            -- 统计 今日淘宝账号订单数量
            (SELECT COUNT(o.id) 
             FROM ya_shop_order AS o 
             WHERE o.member_account_id = a.id and a.store_platform_id in({$taobao_str}) and o.is_delete =0 and o.status in ({$status_str})
               AND o.meet_time >= CURDATE()) AS order_account_today_num,
             -- 统计 近7日淘宝账号订单数量
            (SELECT COUNT(o.id) 
             FROM ya_shop_order AS o 
             WHERE o.member_account_id = a.id and a.store_platform_id in({$taobao_str}) and o.is_delete =0 and o.status in ({$status_str})
               AND o.meet_time >= NOW() - INTERVAL 7 DAY ) AS order_account_7day_num,
             -- 统计 近30日淘宝账号订单数量
            (SELECT COUNT(o.id) 
             FROM ya_shop_order AS o 
             WHERE o.member_account_id = a.id and a.store_platform_id in({$taobao_str}) and o.is_delete =0 and o.status in ({$status_str})
               AND o.meet_time >= NOW() - INTERVAL 30 DAY ) AS order_account_30day_num,
             -- 统计 近30日买号订单数量
            (SELECT COUNT(o.id) 
             FROM ya_shop_order AS o 
             WHERE o.member_account_id = a.id  and o.is_delete =0 and o.status in ('.$status_str.')
               AND o.meet_time >= NOW() - INTERVAL 30 DAY ) AS order_account_30_day_num
            FROM ya_member_account AS a
            -- 关联买手	
            LEFT JOIN ya_member AS member ON a.member_id = member.member_id
            where 
            member.member_id = {$member_id}
            and member.is_disable=0
            and member.is_delete = 0
            and a.is_disable=0
            and a.is_delete = 0
            {$member_where_sql}
        SQL;
        $member_list = Db::query($member_sql);
        foreach ($member_list as $key=>$val){
            //用户每天限制接单数
            if (isset($setting['order_member_today_num']) && $setting['order_member_today_num'] > 0 && $val['order_member_today_num'] >= $setting['order_member_today_num']) {
                $res['msg'] = '对不起，您今日订单数已到达最高';
                return $res;
            }
            //用户近7天限制接单数
            if (isset($setting['order_member_7day_num']) && $setting['order_member_7day_num'] > 0 && $val['order_member_7day_num'] >= $setting['order_member_7day_num']) {
                $res['msg'] = '对不起，您本周订单数已到达最高';
                return $res;
            }
            //用户近30天限制接单数
            if (isset($setting['order_member_30day_num']) && $setting['order_member_30day_num'] > 0 && $val['order_member_30day_num'] >= $setting['order_member_30day_num']) {
                $res['msg'] = '对不起，您本月订单数已到达最高';
                return $res;
            }
            //用户进行中单数限制
            if (isset($setting['order_member_conduct_num']) && $setting['order_member_conduct_num'] > 0 && $val['order_member_conduct_num'] >= $setting['order_member_conduct_num']) {
                $res['msg'] = '对不起，您未完成的订单数已到达最高';
                return $res;
            }
            //用户操作中单数限制
            if (isset($setting['order_member_operation_num']) && $setting['order_member_operation_num'] > 0 && $val['order_member_operation_num'] >= $setting['order_member_operation_num']) {
                $res['msg'] = '您还有待操作的订单需要处理';
                return $res;
            }
            //待接单数限制
            if(isset($val['order_member_pending']) && $val['order_member_pending']>0){
                $res['msg'] = '您有待接订单请前往处理';
                return $res;
            }
            //新手期条件限制
            $member_day = self::returnDay($val['create_time']);
            if (isset($setting['order_new_member_num']) && $setting['order_new_member_num'] > 0 && $member_day <= $setting['order_new_member_num']) {
                $order_member_principal = $val['order_member_principal'];
                //新手前几单接单限制金额
                if (isset($setting['order_new_member_price']) && $setting['order_new_member_price'] > 0 && $order_member_principal > $setting['order_new_member_price']) {
                    $res['msg'] = '对不起，您初期订单金额已到达最高';
                    return $res;
                }
                //新手前30天限制接单数
                if (isset($setting['order_new_member_30day_num']) && $setting['order_new_member_30day_num'] > 0 && $val['order_member_total'] > $setting['order_new_member_30day_num']) {
                    $res['msg'] = '对不起，您初期订单数已到达最高';
                    return $res;
                }
            }
            //今日淘宝账号订单数量
            if (isset($setting['order_account_today_num']) && $setting['order_account_today_num'] > 0 && $val['order_account_today_num'] >= $setting['order_account_today_num']) {
                $res['msg'] = '对不起，您的买号今日订单数已到达最高';
                return $res;
            }
            //近7日淘宝账号订单数量
            if (isset($setting['order_account_7day_num']) && $setting['order_account_7day_num'] > 0 && $val['order_account_7day_num'] >= $setting['order_account_7day_num']) {
                $res['msg'] = '对不起，您的买号本周订单数已到达最高';
                return $res;
            }
            //近30日淘宝账号订单数量
            if (isset($setting['order_account_30day_num']) && $setting['order_account_30day_num'] > 0 && $val['order_account_30day_num'] >= $setting['order_account_30day_num']) {
                $res['msg'] = '对不起，您的买号本月订单数已到达最高';
                return $res;
            }
        }
        if($member_list){
            /***************************平台匹配***********************************************/
            $store_platform_ids  = array_unique(array_column($member_list,'store_platform_id'));
            $store_platform_ids =self::updateArray($store_platform_ids,$taobao_ids);
            $order_where = " and a.store_platform_id in (".implode(',',$store_platform_ids).")";
            /***************************查询买手是否指定分组***********************************************/
            $merchant_ids = Db::query("SELECT mer_id from ya_merchant_attributes where group_id in(
                                            SELECT group_id from ya_member_attributes where member_id = ".$member_id."
                                        ) GROUP BY mer_id");
            if($merchant_ids){
                $order_where .=" and a.merchant_id in (".implode(',',array_column($merchant_ids,'mer_id')).")";
            }
            /***************************接单账号黑名单***********************************************/
            //等待接单条件中使用
            $merchant_blacklist = Db::name('merchant_blacklist')
                ->where('member_id',$member_id)
                ->whereIn('member_account_id',array_column($member_list,'member_account_id'))
                ->where('is_disable',0)
                ->where('is_delete',0)
                ->field('mer_id')
                ->group('mer_id')
                ->select()
                ->toArray();
            if($merchant_blacklist){
                $order_where .=" and a.merchant_id not in (".implode(',',array_column($merchant_blacklist,'mer_id')).")";
            }
            /***************************订单id***********************************************/
            if($type==2 && $shop_order_id){
                $order_where .=" and a.id=".$shop_order_id;
            }
            /***************************订单查询***********************************************/
            $o_select = ShopOrderModel::getStatus('o_select',1);//待自选
            $member_ids = implode(',',array_unique(array_column($member_list,'member_id')));
            $member_account_ids = implode(',',array_unique(array_column($member_list,'member_account_id')));
            $o_taking = ShopOrderModel::getStatus('o_taking',1);//待接单
            $ptbt = ShopProductTypeModel::PTBT;
            $time = date('Y-m-d H:i:s');
            $order_sql = <<<SQL
                SELECT * from ya_shop_order as a
                where 
                (a.status = {$o_taking} 
                or (a.status = {$o_select} and a.pending_member_id in ({$member_ids}) and a.pending_member_account_id in ({$member_account_ids})))
                and a.shop_product_type_code <> '{$ptbt}'
                and (a.pending_time is null or a.pending_time < '{$time}')
                {$order_where}
                order by a.status asc
            SQL;
            $order_list = Db::query($order_sql);
            $order_ids = [];
            $range_codes =SettingPriceRangeModel::RANGE_CODES;
            /***************************通过账号过滤订单***********************************************/
            foreach ($order_list as $o_key=>$order){
                /***************************店铺复购天数限制***********************************************/
                $repurchase_data = self::getRepurchaseData($order['merchant_id'],$order['merchant_shop_id']);
                $is_purchase = false;
                if($repurchase_data && isset($repurchase_data['repurchase_days']) && $repurchase_data['repurchase_days']>0 && isset($repurchase_data['shop_ids']) && $repurchase_data['shop_ids']){
                    $is_purchase = true;
                }
                /***************************增值条件过滤***********************************************/
                $price_condition_list= self::getPriceCondition($order,$range_codes);
                $is_price_condition = false;
                foreach ($member_list as $key=>$val){
                    $s_platform_ids =self::updateArray([$val['store_platform_id']],$taobao_ids);
                    if(in_array($order['store_platform_id'], $s_platform_ids)){
                        foreach ($price_condition_list as $pcl_key=>$pcl_val){
                            $condition_value = json_decode($pcl_val['condition_value'], true);
                            $filed_name = 'price_range_'.$pcl_val['setting_price_range_id']."_".$pcl_val['setting_price_condition_type'];
                            switch ($pcl_val['setting_price_range_code']){
                                case $range_codes[0]://年龄限制
                                    if(array_key_exists($filed_name, $condition_value) &&  $val['age_index']!=$condition_value[$filed_name]){
                                        $is_price_condition = true;
                                    }
                                    break;
                                case $range_codes[1]://禁止狂刷号
                                    if($val['order_account_30_day_num']>$setting['order_account_crazy_num']){
                                        $is_price_condition = true;
                                    }
                                    break;
                                case $range_codes[2]://性别限制
                                    if(array_key_exists($filed_name, $condition_value)){
                                        $spc_labels = explode(',',$pcl_val['spc_label']);
                                        $spc_values = explode(',',$pcl_val['spc_value']);
                                        $sex = $val['sex']==1?'男':($val['sex']==2?'女':'保密');
                                        if(array_search($condition_value[$filed_name], $spc_values) === false || $spc_labels[array_search($condition_value[$filed_name], $spc_values)]!=$sex){
                                            $is_price_condition = true;
                                        }
                                    }
                                    break;
                                case $range_codes[3]://帐号等级限制
                                    if(array_key_exists($filed_name, $condition_value)){
                                        $spc_labels = explode(',',$pcl_val['spc_label']);
                                        $spc_values = explode(',',$pcl_val['spc_value']);
                                        $spc_index = array_search($condition_value[$filed_name], $spc_values);
                                        $level_value = self::getLevelValue($spc_labels[$spc_index]);
                                        if($level_value==null){
                                            $level_value = 0;
                                        }
                                        if($spc_index === false || $val['level']<$level_value){
                                            $is_price_condition = true;
                                        }
                                    }
                                    break;
                                case $range_codes[4]://淘气值限制
                                    if(array_key_exists($filed_name, $condition_value)){
                                        $spc_labels = explode(',',$pcl_val['spc_label']);
                                        $spc_values = explode(',',$pcl_val['spc_value']);
                                        $spc_index = array_search($condition_value[$filed_name], $spc_values);
                                        $integral =0;
                                        if (preg_match('/\d+(\.\d+)?/', $spc_labels[$spc_index], $matches)) {
                                            $integral = $matches[0];
                                        }
                                        if($spc_index === false || $val['integral']<$integral){
                                            $is_price_condition = true;
                                        }
                                    }
                                    break;
                                case $range_codes[5]://地区限制
                                    if(array_key_exists($filed_name, $condition_value)){
                                        $spc_labels = explode(',',$pcl_val['spc_label']);
                                        $spc_values = explode(',',$pcl_val['spc_value']);
                                        $cv_values = $condition_value[$filed_name];
                                        $regions = [];
                                        foreach ($spc_values as $spcv_key=>$pscv_val){
                                            if(in_array($pscv_val,$cv_values)){
                                                array_push($regions,$spc_labels[$spcv_key]);
                                            }
                                        }
                                        $region_path = Db::name('setting_region')->where('region_id',$val['region_id'])->value('region_path');
                                        $region_path = explode(',',$region_path);
                                        $region_intersect = array_intersect($regions,$region_path);
                                        if(!$region_intersect || count($region_intersect)<=0){
                                            $is_price_condition = true;
                                        }
                                    }
                                    break;
                                case $range_codes[6]://复购只允许之前做过
                                    //检查订单商家是否勾选复购，有复购则复购天数限制失效
                                    $is_purchase = false;
                                    //查询复购数量
                                    $repeat_num = Db::name('shop_order')
                                        ->where('is_delete',0)
                                        ->where('merchant_id',$order['merchant_id'])
                                        ->where('merchant_shop_id',$order['merchant_shop_id'])
                                        ->where('member_id',$val['member_id'])
                                        ->where('member_account_id',$val['id'])
                                        ->whereIn('status',$status_str)
                                        ->count();
                                    if($repeat_num<=0){
                                        $is_price_condition = true;
                                    }
                                    break;
                                case $range_codes[7]://仅限做过商品浏览单的可接,请谨慎勾选
                                    $third_ids = Db::name('shop_product_goods')->where('shop_product_id',$order['shop_product_id'])->column('third_id');
                                    $llrw_num = Db::name('shop_product_goods')->alias('a')
                                        ->leftJoin('shop_order','shop_order.shop_product_id = a.shop_product_id')
                                        ->where('shop_order.is_delete',0)
                                        ->where('shop_order.merchant_id',$order['merchant_id'])
                                        ->where('shop_order.member_id',$val['member_id'])
                                        ->where('shop_order.member_account_id',$val['id'])
                                        ->where('shop_order.shop_product_type_code',ShopProductTypeModel::LLRW)
                                        ->whereIn('shop_order.status',$status_str)
                                        ->whereIn('a.third_id',$third_ids)
                                        ->count();
                                    if($llrw_num<=0){
                                        $is_price_condition = true;
                                    }
                                    break;
                                case $range_codes[8]://旺旺照妖镜验号
                                    if($val['is_verify'] != 1 || $val['authority'] === null || $val['authority']>$setting['order_account_verify_authority']){
                                        $is_price_condition = true;
                                    }
                                    break;
                                case $range_codes[9]://88会员
                                    if($val['is_member'] != 1){
                                        $is_price_condition = true;
                                    }
                                    break;
                            }
                            if($is_price_condition){
                                break;
                            }
                        }
                        //查询买号或者买家是否达到店铺复购限制
                        if($is_purchase){
                            $purchase_num = Db::name('shop_order')
                                ->where('is_delete',0)
                                ->where('merchant_id',$order['merchant_id'])
                                ->where('merchant_shop_id',$order['merchant_shop_id'])
                                ->when(true,function ($query)use($setting,$val){
                                    if($setting['order_repurchase_type']==2){
                                        $query->where('member_id',$val['member_id']);
                                    }else{
                                        $query->where('member_account_id',$val['id']);
                                    }
                                })
                                ->where('meet_time','>=',date('Y-m-d H:i:s', strtotime('-'.$repurchase_data['repurchase_days'].' days')))
                                ->whereIn('status',$status_str)
                                ->count();
                            if($purchase_num>0 && $setting['order_repurchase_type']==2){
                                $is_price_condition = true;
                                break;
                            }else if($purchase_num>0){
                                $is_price_condition = true;
                                continue;
                            }
                        }
                        //当该买号适合接该订单
                        if(!$is_price_condition){
                            if($type==2){
                                array_push($order_ids,$order);
                            }else{
                                array_push($order_ids,$order['id']);
                            }
                        }
                    }
                }
            }
            $res['code'] = 1;
            $res['data'] = $order_ids;
            $res['msg'] = "成功";
        }
        return $res;
    }
}
